ObjectInputStream and default constructor in Tiger
Leonardo Crespo
Ranch Hand
Joined: Jul 03, 2005
Posts: 31
posted
0
Hi all. Can anyone give me a hand on this issue?
In page 338 of Complete Java 2 Certification, Study Guide, 5th edition (Tiger), it says: ----------- Notice that the readObject() mechanism of ObjectInputStream relies on the existence of a no-args constructor for any class that implements Externalizable. If an externalizable class has no no-args constructor, the readObject() method will throw java.io.InvalidClassException. -----------
I checked in the API and it says:
However, this is not true.
This is the class i'm serializing and i'm not providing a default constructor. Since i'm providing a constructor, the compiler does not create the default one.
(ps: just to clarify things, Fusca equals Beagle, it's a type of car)
This code compiles just fine and i dont get errors in deserialization either.
Why is that?
Thank you very much. Leonardo.
Leonardo Crespo
Joyce Lee
Ranch Hand
Joined: Jul 11, 2003
Posts: 1392
posted
0
Hi Leonardo,
Notice that the readObject() mechanism of ObjectInputStream relies on the existence of a no-args constructor for any class that implements Externalizable. If an externalizable class has no no-args constructor, the readObject() method will throw java.io.InvalidClassException.
Here's an example which demostrates an externalizable class without a no-arg constructor:
Without a no-arg constructor, it'll throw InvalidClassException. Now try uncomment the no-arg constructor and run again. It should run without problem.