Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Serializable (are all variables affected?)

I want to kow whether the attribute foo will also be serialized in the following example or not (written out of my mind):

public class Example implements Serializable {
     private String a = "a";
     private Foo foo = new Foo("a");
}

NOTE: Class Foo only holds an attribute a and does not implement Serializable

If Foo is not Serializable, I have the other problem, that Foo cannot implement Serializable, because it is provided by an Api Call from an external .jar-file. Also in my concrete case Foo holds also an class Bar which is also not Serializable.

like image 862
Sonnenhut Avatar asked Sep 07 '25 02:09

Sonnenhut


1 Answers

If Foo is not Serializable, an attempt to serialize an instance of Example with a non-null foo will result in a NotSerializableException, unless foo is declared transient.

You could have found that out sourself quite easily by simply trying it out.

Update: In order to be able to serialize instances of Example when you cannot change Foo but need to preserve its contents, you can implement the readObject() and writeObject() methods as described in the API doc of Serializable

like image 83
Michael Borgwardt Avatar answered Sep 09 '25 16:09

Michael Borgwardt