3

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

Not a bug
  • 4,286
  • 2
  • 40
  • 80
HashUser123
  • 57
  • 2
  • 6

5 Answers5

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
  • 44,383
  • 11
  • 84
  • 103
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
  • 412,405
  • 93
  • 575
  • 722
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,271
  • 17
  • 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,664
  • 1
  • 14
  • 18
0

At the time of serialization, if some filed value, we dont want to save in files we use transient in java. Similarly some fields in class are not able to serialisable but class we extended as a serialisable at that time we use Transient field


class Cat implements serializable {
 private int eyes;
 private String voice;
}

Use transient for excluding some fields which ll not come under serializable.


class Cat implements serializable {
 private int eyes;
 private transient String voice;
}
borchvm
  • 3,533
  • 16
  • 44
  • 45