开发者

Passing a generic class to a java function?

开发者 https://www.devze.com 2022-12-31 15:42 出处:网络
Is it possible to use Generics when passing a class to a java function? I was hoping to do something like this:

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消