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.)
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.
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).
Yes. If a parent implements Serializable then any child classes are also Serializable .
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.
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 {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With