开发者

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 canno开发者_如何转开发t 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.


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


If the foo instance is not Serializable, the serialisation of Example will fail at runtime - try it!

You can provide a custom serialised form of Example by providing readObject and writeObject methods.


If Foo is not serializable, trying to serialize an Example instance will throw a runtime exception. You need to make it serializable, or mark the foo field as transient. But in the latter case, when deserializing the example, foo will be null.


See NotSerializableException.

Only transient fields are not omitted during serialization.


Then no.

You'll get this:

   java.io.NotSerializableException: Foo


I think you will need to deal with custom serialization if you want to get your Example object to be serialized. here you go: 1. Given the Foo comes from the jar you can't change, make it transient (otherwise you'll get an exception in runtime, as was stated before). 2. Define "readObject"/"writeObject" and from there manage your serialization process. - Call the defaultWriteObject to make Java serializing what it can serialize. extract the state of the foo class (in your example, the internal state of Foo is "a") - serialize explicitly the "a" The same should be done during the deserialization: - invoke the default deserialization mechanism - deserialize "a" (you know that right after the default data there is your custom String in the stream) - create the Foo instance from A from the readObject.

In general I would recommend to read about this in Joshua Bloch's "Effective Java" book - he has a nice coverage of this topic there. In addition there are a lot of examples in internet

For example Serialization Example

Hope this helps

Mark

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜