Is it possible to use Generics when passing a class to a java function?
I was hoping to do something like this:
public static class DoStuff
{
public <T extends Class<List>> void doStuffToList(T className)
{
System.out.println(className);
}
public void test()
{
doStuffToList(List.class); // compiles
doStuffToList(ArrayList.class); // compiler error (undesired behaviour)
doStuffToList(Integer.class); // compiler error (desired behaviour)
}
}
Ideally the List.class and ArrayList.class lines would work fine, but the Integer.class line would cause a compile error. I could use Class as my type instead of T extends Class<List> but then I won’t catch the Integer.class case above.
You are passing a
Classafter all – the parameter should be of typeClass, and its type parameters should be limited.Actually,
<T extends Class<..>meansT == Class, becauseClassisfinal. And then you fix the type parameter of the class toList– not anyList, justList. So, if you want your example to work, you’d need:but this is not needed at all.