How to serialize a non-serializable in Java?

前端 未结 5 1747
太阳男子
太阳男子 2020-11-27 19:54

How can I serialize an object that does not implement Serializable? I cannot mark it Serializable because the class is from a 3rd party library.

5条回答
  •  余生分开走
    2020-11-27 20:35

    You can't serialise a class that doesn't implement Serializable, but you can wrap it in a class that does. To do this, you should implement readObject and writeObject on your wrapper class so you can serialise its objects in a custom way.

    • First, make your non-serialisable field transient.
    • In writeObject, first call defaultWriteObject on the stream to store all the non-transient fields, then call other methods to serialise the individual properties of your non-serialisable object.
    • In readObject, first call defaultReadObject on the stream to read back all the non-transient fields, then call other methods (corresponding to the ones you added to writeObject) to deserialise your non-serialisable object.

    I hope this makes sense. :-)

提交回复
热议问题