It's not clear whether you want to perform the check at compile-time or at runtime. If you simply want to ensure that the list parameter passed to the method contains certain types of objects, then redefine T
appropriately.
For example, to ensure that the compiler will only allow a List<Comparable>
to be passed to this method, redefine T
as:
public <T extends Comparable<? super T>> List<T> doSth(List<T> l) {
// Method body omitted
}
You can then use method-overloading (instead of an if-else statement), to ensure the correct code is called for any value of T
. In other words, replace this:
public <T> List<T> doSth(List<T> l) {
if(T extends Comparable) {
// do one thing
} else {
// do another
}
return null
}
with these:
public <T extends Comparable<? super T>> List<T> doSth(List<T> l) {
// do one thing
return null;
}
public <T> List<T> doSth(List<T> l, Class<T> clazz) {
// do another
return null;
}
However, you need to remember choosing which overloaded method to call and generic-type checking is compile-time only! For example, the following code:
List<? extends Serializable> alist = new ArrayList<Integer>();
doSth(alist);
will actually call the second doSth
method, because the compile-time type parameter (? extends Serializable
) does not implement Comparable
, even though the runtime type parameter (Integer
) does.