Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics - is it possible to restrict T to be Serializable?

Tags:

java

generics

Is it possible to make something like this? I know that implements cannot be in the <>, but I want to restrict the T to be Serializable somehow.

public class Clazz<T implements Serializable> {
    ...
}
like image 802
user219882 Avatar asked Aug 16 '11 10:08

user219882


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.

How can we restrict generics to a subclass of particular class?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.

Which are the advantages and disadvantages of generics in Java?

Advantage of Java Generics 1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other objects. Without Generics, we can store any type of objects. List list = new ArrayList();


2 Answers

public class Clazz<T extends Serializable> {
    ...
}
like image 142
Heisenbug Avatar answered Sep 23 '22 10:09

Heisenbug


Just use extends instead of implements.

like image 30
Ingo Avatar answered Sep 24 '22 10:09

Ingo