Please see the following code. I wrote the code by myself. But it may look like the code on Serialization in K & B book.
Please see that two lines are marked in boldface.
I have a query on this code.
1. If I comment out Line 1 and Line 2 ( in boldface ) , the code will show the expected output. We know the reason.
2. If I comment out only Line 2, the code is showing the expected output.
3. If I comment out only Line 1, EOFException is thrown at runtime. But why ?
Please let me know why Exception is thrown in the 3rd scenario. Thanks in advance.
( Jesper Young: Added code tags )
At line 1 you are writing you object to a file writing.ser, you can open and see the written object in bytes.
At line 2 you are reading same object from the same file.
Now if you comment line 1, then you will not write anything in your file. File will be blank.
Now if you read blank file, you will get java.io.EOFException.
Both methods readObject and writeObject has private access. But if I replace "private" with "public", the code doesn't work. How can this be? How this is implemented by J2SE? I really confused with this for a long time. :?:
Banashri Mandal wrote:Thanks. But what about the first scenario, then ? If I comment out both Line 1 and Line 2, does not the code write anything to the file ?
The code gives expected output.
Yes for the first scenario it neither writes anything to the file not reads from it.
It just prints what you have set to Desktop object at the starting of your program.
Punit Singh wrote:That is very advance concept Treimin, I only know private method writeObject() is called internally by
ObjectOutputStream.writeObject(Object) method. It must be using reflection inside and must be checking for private access of these methods.
Can we use the reflection API to check the private access? :?:
Punit Singh wrote:See this link's 1st and 2nd reply to get some idea about power of reflection.
Thanks for the link
It seems we have to study about Reflection API too.