5

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?

1
  • Sure! Try implementing the Object readResolve() throws ObjectStreamException method, and set the defaults in there. See the spec for precise details on how this works with ObjectInputStream. Commented Jan 11, 2016 at 18:01

1 Answer 1

3

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;
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any reason the three "special" fields should be declared as transient? IIUC transient means "should not be serialized" in JAVA.
@TT as transient fields they will be ignored by ObjectOutputStream.defaultWriteObject() and ObjectInputStream.defaultReadObject()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.