简体   繁体   中英

Passing a generic class to a java function?

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM