简体   繁体   中英

Selective serialization of Java Object

Consider a case where I've 10 fields in my java class. What I want is , do some special handling for few of them ( say 3) and rest of the fields been serialized via default ObjectOutputStream implementation. Is there a way to achieve this ?

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

thanks

You could do the following:

  • declare the three special fields as transient
  • implement writeObject(ObjectOutputStream out) and in this method:
  • use ObjectOutputStream.defaultWriteObject() to write all other fields in the default way
  • then add your custom serialization for the special fields

and add analog implementations to read the object.

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;
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM