Passing a generic class to a java function?

Posted by rodo on Stack Overflow See other posts from Stack Overflow or by rodo
Published on 2010-05-18T05:53:23Z Indexed on 2010/05/18 6:00 UTC
Read the original article Hit count: 137

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about generics