citress
citress

Reputation: 909

Java - Handle serialization only in superclass

I have a hierarchy of domain classes in my web application, which I want to make serializable. All domain classes inherit from an abstract base class. I plan to override readObject and writeObject in the abstract base class. Is there a way to make all subclasses defer to the super class for serialization, so that subclasses do not serialize any of their own fields?

I'm using FST Serialization - if the above is not possible in Java, is there a way to, say for example, specify a "serialization strategy" for objects of a certain type?

public abstract class Base implements Serializable {

    private void writeObject(java.io.ObjectOutputStream stream) 
         throws IOException {
       ...
    }

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

public class Person extends Base {

   // I don't want Person class to do anything for serialization
}

Update: I have more than a hundred subclasses, each subclass has several fields. These classes make up the domain model in my web application. I was hoping to find an easier way to handle this other than to specify 'transient' on every field in every class.

Background: I am serializing session state in order to allow saving to a cache server. Our session object has references to domain objects. Rather than saving the entire domain object, I was hoping to only save part of the domain object, and re-construct it when the session object gets "bounced" to another server.

Upvotes: 1

Views: 528

Answers (1)

Andy Turner
Andy Turner

Reputation: 140328

Is there a way to make all subclasses defer to the super class for serialization, so that subclasses do not serialize any of their own fields?

You can do this the same way you ask any field not to be serialized: make all of the fields in the subclass transient (or static).

But this is quite a restriction on the subclasses, and a burden on the programmer to remember to make all fields transient, and in some sense it makes fields in the subclasses of limited use. Consider carefully why you are trying to stop subclass fields being serialized.

Upvotes: 1

Related Questions