Serializable subclass of non-serializable parent class

前端 未结 2 1032
梦毁少年i
梦毁少年i 2020-12-20 14:52

I am hitting a brickwall with serialization of a subclass of Location in android/java

Location is not serializable. I have a first subclass called FALocation that do

2条回答
  •  囚心锁ツ
    2020-12-20 15:11

    Is it absolutely necessary to serialize the Location? maybe you could mark it as transient, and obtain it dynamically after deserializing the object. (Anyway, from the documentation ) :

    Q: If class A does not implement Serializable but a subclass B implements Serializable, will the fields of class A be serialized when B is serialized?

    A: Only the fields of Serializable objects are written out and restored. The object may be restored only if it has a no-arg constructor that will initialize the fields of non-serializable supertypes. If the subclass has access to the state of the superclass it can implement writeObject and readObject to save and restore that state.

    So, if the subclass has access to the fields of its non-serializable superclass(es) it can use the writeObject and readObject protocol to implement serialization. Otherwise, there will be fields that won't be possible to serialize.

提交回复
热议问题