Selective serialization of a Java object

Consider the case when I have 10 fields in my java class. I want to do some special processing for some of them (say 3), and the rest of the fields have been serialized using the default ObjectOutputStream implementation. Is there any way to achieve this?

I can provide an implementation of writeObject (ObjectOutputStream os) in my class to specifically handle these 3 fields, but as by default for the rest of the fields.

thanks

+4
source share
1 answer

You can do the following:

  • declare three special fields as transitional
  • implement writeObject(ObjectOutputStream out)in this method:
  • use ObjectOutputStream.defaultWriteObject()to write all other default fields.

.

public class MyClass implements Serializable
{
    private void writeObject(java.io.ObjectOutputStream out) throws IOException
    {
        out.defaultWriteObject();
        // add code to write the special fields
    }

    private void readObject(java.io.ObjectInputStream in) throws IOException
    {
        in.defaultReadObject();
        // add code to read the special fields
    }

    private transient int special1;
    ...
}
+3

Source: https://habr.com/ru/post/1623808/


All Articles