Reputation: 43
Problem: class A implements Serializable class B extends A implements Serializable
Now I Serialize using the class B only as runtime-type. So I have a list:
List<A> lst = new ArrayList<A>();
lst.add(new B());
...
objectOutputStream.writeObject(lst.get(i)); //this write compiler-type A, runtime-type B
If I now deserialize it, i get java.io.OptionalDataException Errors. What I'm wondering anyhow is how, my object becomes the correct runtime-type. Deserializing:
A a = (A) objectInputStream.readObject();
Does this lead to an runtime type of class B if it was one at serialization-time, or do I have to overwrite the default serialization for earch sub-class of A?
Hope I didnt miss any obvious things.
Thanks in advance : )
EDIT:
Thanks to all the answers, they really helped alot understanding my own mistakes.
The exception was thrown because I (as answered) used in.read(arr); that lead to not fully read data, and so it could not deserialize the objects correclty (of course not) - after changing it to readFully it worked as expected.
Upvotes: 0
Views: 564
Reputation: 33534
Ok..try this......
1. First of all serializable is a marker/tag interface, which say the objects of this class are allowed to be serialized, and When a Super class is serializable its Sub class will be automatically serializable...so No need to make B which extends A to be serializable.
2. Now when you say use readObject() to read the objects back, it will be in Object form, and thats the reason you need to cast it in its type.
Eg:
GamePlayer gp1 = (GamePlayer) os.readObject(); //os is ObjectInputStream instance
Upvotes: 0
Reputation: 114
With the given information, I cannot determine why you got the OptionalDataException. A is Serializable, hence B will be serializable as B extends A. Assuming list.get(i) is the object B, then objectOutputStream.writeObject(list.get(i)) will write object B to the stream. And when you read it back, it will return the object B.
The argument of type erasure is irrelevant because method ObjectOutputStream.writeObject accepts Object as the argument.
Do you define private method writeObject and readObject for class A or B? If you define those methods, please make sure they read and write objects and primitive data in correct order.
Upvotes: 1