What happens if your Serializable class contains a member which is not serializable? How do you fix it?
-
1do you want that member to be saved to disk as well when you perform IO on it? if not, you need to mark it as `Transient` – Hrishikesh Jan 31 '14 at 09:27
-
http://stackoverflow.com/q/910374/1686291 – Not a bug Jan 31 '14 at 09:29
4 Answers
It'll throw a NotSerializableException when you try to Serialize it. To avoid that, make that field a transient field.
private transient YourNonSerializableObject doNotSerializeMe; // This field won't be serialized
- 43,125
- 11
- 82
- 101
One of the fields of your class is an instance of a class that does not implement Serializable, which is a marker interface (no methods) that tells the JVM it may serialize it using the default serialization mechanism.
If all the fields of that class are themselves Serializable, easy - just add implements Serializable to the class declaration.
If not, either repeat the process for that field's class and so on down into your object graph.
If you hit a class that can't, or shouldn't, be made Serializable, add the transient keyword to the field declaration. That will tell the JVM to ignore that field when performing Serialization.
- 389,931
- 88
- 552
- 692
The class will not be serialisable, unless the field is declared transient (which will prevent the field from being serialised, i.e. it will not be saved).
If you can, I suggest to make that member serialisable, otherwise you have to use writeObject and readObject to write and/or read the field manually. See the docs for information on these methods: http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html
- 3,191
- 15
- 32
@HashUser123: use transient keyword before the field which you do not want to serialized. For ex:
private transient int salary;
- 2,588
- 1
- 13
- 18