user443854
user443854

Reputation: 7455

Is there a way to deserialize part of an object in Java?

Hypothetical scenario: output stream of objects of type Message that implement Serializable. Message has members Header and Body. Header is small and Body can be large. Say I want to write a filter based on info in the Header: is there a way to do it without having to deserialize Body?

Upvotes: 3

Views: 632

Answers (3)

shams
shams

Reputation: 3508

You can write a custom readObject() to read only the fields you want. If you only want to read the Header, you need to take care that you serialize the Header first and then the body. Then in your custom readObject() method you can choose to read only the first element.

public class Message implements Serializable {

  private transient String header;
  private transient String body;

  ...
  // custom write object that writes header first and then body
  private void writeObject(java.io.ObjectOutputStream oos)
      throws IOException {
    oos.defaultWriteObject();
    // explicitly store the transient fields
    oos.writeObject(header);
    oos.writeObject(body);
  }

  private void readObject(java.io.ObjectInputStream ois) 
      throws IOException, ClassNotFoundException {
    ois.defaultReadObject();
    // explicitly read in the transient fields
    header = (String) ois.readObject();
    if (needBody()) { // use some static/thread local variable to set this condition
      body = (String) ois.readObject();
    }
  }
}

Upvotes: 1

Luis Casillas
Luis Casillas

Reputation: 30227

You just discovered one of the weaknesses of object-oriented programming compared to databases: "What if I just want half of a Customer object?"

What I would say is that you need to split your Message class into something like MessageHeader, with the header information and no reference to the body, and a MessageBody class that has the body and a key that can be used to look up the header data. Then you need to store and retrieve the serialized MessageHeader and MessageBody objects separately.

Upvotes: 2

bragboy
bragboy

Reputation: 35542

You shall NOT serialize Body in the first place by declaring it transient.

But if you already have serialized the Message object, there is no way to selectively deserialize specific members.

Upvotes: 3

Related Questions