3

What happens if your Serializable class contains a member which is not serializable? How do you fix it?

Not a bug
  • 4,256
  • 1
  • 38
  • 72
HashUser123
  • 57
  • 1
  • 6

4 Answers4

2

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
Rahul
  • 43,125
  • 11
  • 82
  • 101
2

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.

Bohemian
  • 389,931
  • 88
  • 552
  • 692
0

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

Njol
  • 3,191
  • 15
  • 32
0

@HashUser123: use transient keyword before the field which you do not want to serialized. For ex:

private transient int salary;
Suneet Bansal
  • 2,588
  • 1
  • 13
  • 18