Home » Java » inheritance – How to serialize child as parent object in Java-Exceptionshub

inheritance – How to serialize child as parent object in Java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a common TransfertObject who need to be serialized between server and client.
The DatabaseObject has the same field + some db specific fields and some annotations but is known only by the server side.
I made the DatabaseObject extends the TransfertObject, but when I serialize it, I can’t deserialize on the client it because java.lang.ClassNotFoundException on the DatabaseObject.
How can I serialize my DatabaseObject as a TransfertObject ?

public class TransfertObject implements Serializable {
   private String transferredProperties;
}

public class DatabaseObject extends TransfertObject {
   private String dbProperties;
}

I know I can make dbProperties transient but that doesn’t resolve the ClassNotFoundException

So far the only workaround I found was to copy properties from one object to the other before serializing it.

public TransfertObject asTransfertObject(DatabaseObject dbObj) {
    TransfertObject transObj = new TransfertObject();
    BeanUtils.copyProperties(dbObj, transObj);
    return transObj;
}

I think could also do the same with the writeReplace method

public class DatabaseObject extends TransfertObject {
   private String dbProperties;

   private Object writeReplace() throws ObjectStreamException {
      TransfertObject transObj = new TransfertObject();
      transObj.transferredProperties = this.transferredProperties;
      // copy other properties
      return transObj;
   }
}

But that doesn’t remove the burden of copying every parent properties.

Isn’t there a way to “more than cast” my object for serialization ?

How to&Answers: