Reputation: 57
What happens if your Serializable class contains a member which is not serializable? How do you fix it?
Upvotes: 3
Views: 6687
Reputation: 31
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;
}
Upvotes: 0
Reputation: 45060
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
Upvotes: 2
Reputation: 424973
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
.
Upvotes: 3
Reputation: 2702
@HashUser123: use transient keyword before the field which you do not want to serialized. For ex:
private transient int salary;
Upvotes: 0
Reputation: 3279
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
Upvotes: 0