简体   繁体   中英

Deserializing only required fields in Java

Test Class to serialize is as follows:

 public Class Test implements Serializable {
      private static final long serialVersionUID = GENERATED_LONG_VALUE;
      private int val;
      private SomeClass_1 val_1;
      private SomeClass_2 val_2;
      private SomeClass_3 val_3;
      // getter and setter for above
  }

I have serialized Object of above class as BLOB in table.

Now while deserializing I just want val and val_1 . So I have overrided readObject() method in Test class like below.

    private void readObject(java.io.ObjectInputStream stream)
        throws IOException, ClassNotFoundException {

        this.val = (int) stream.readObject();
        this.val_1 = (SomeClass_1) stream.readObject();
    }

But after this also, It is doing stream.readObject() for val_3 and val_4 . I am not understanding why it is happening even I am not reading val_3 and val_4 in stream.readObject() .

PS I am doing serialization on server X , While deserializing it at server Y and class Structure is exactly same at server Y like server X .

If one Server X requires all members of the object to be passed to it, but Server Y doesn't, you might want to:

  1. Look into Externalization . This gives you full control of marshalling and unmarshalling, which seems like what you need.

  2. Send the servers different proxy objects : One which serializes all fields, and one that doesn't. You could create a proxy for data that is to be sent to the servers, passing in the object you want to send. One proxy uses transient , the other doesnt.

  3. Don't send objects, rather than data required to reconstruct the objects on the other side. This relieves stress on the network if the objects you want to send over don't require much data.

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