Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize a generic class in Java?

I have started to read about serialization in Java and little bit in other languages too, but what if I have a generic class and I want to save a instance of it to file.

code example

public class Generic<T> {
  private T key;
  public Generic<T>() {
    key = null;
  }
  public Generic<T>(T key) {
    this.key = key;
  }
}

Whats the best way to save this kind of Object? (Of course there is more in my real ceneric class, but I'm just wondering the actual idea.)

like image 844
Leolian Avatar asked May 31 '13 07:05

Leolian


People also ask

How do you serialize a generic object in Java?

As per the Java Object Serialization Specification, we can use the writeObject() method from ObjectOutputStream class to serialize the object. On the other hand, we can use the readObject() method, which belongs to the ObjectInputStream class, to perform the deserialization.

Can class be serialized in Java?

Only the objects of those classes can be serialized which are implementing java. io. Serializable interface. Serializable is a marker interface (has no data member and method).

Can we serialize child class in Java?

Yes. If a parent implements Serializable then any child classes are also Serializable .

Can we serialize class without implementing Serializable interface?

If the superclass is Serializable, then by default, every subclass is serializable. Hence, even though subclass doesn't implement Serializable interface( and if its superclass implements Serializable), then we can serialize subclass object.


1 Answers

You need to make generic class Serializable as usual.

public class Generic<T> implements Serializable {...}

If fields are declared using generic types, you may want to specify that they should implement Serializable.

public class Generic<T extends Serializable> implements Serializable {...}

Please be aware of uncommon Java syntax here.

public class Generic<T extends Something & Serializable> implements Serializable {...}

like image 199
Grzegorz Żur Avatar answered Sep 18 '22 12:09

Grzegorz Żur