tags:

views:

87

answers:

2

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.

+4  A: 

ArrayList.class is of type Class<ArrayList>, while the parameter should be a Class<List>. These types are not compatible, for the same reason that List<Integer> is not a List<Number>.

You can define the function as follows, and get the expected behavior:

public void doStuffToList(Class<? extends List> className)
Eyal Schneider
+8  A: 
public <T extends List> void doStuffToList(Class<T> clazz)

You are passing a Class after all - the parameter should be of type Class, and its type parameters should be limited.

Actually, <T extends Class<..> means T == Class, because Class is final. And then you fix the type parameter of the class to List - not any List, just List. So, if you want your example to work, you'd need:

public <T extends Class<? extends List>> void doStuffToList(T clazz)

but this is not needed at all.

Bozho
Thanks, exactly what I was looking for.
rodo