Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a generic class to a java function?

Tags:

java

generics

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.

like image 918
rodo Avatar asked May 18 '10 05:05

rodo


People also ask

How do I pass generics in Java?

Generics Work Only with Reference Types:When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);

Can we inherit generic class in Java?

It inherits all members defined by super-class and adds its own, unique elements. These uses extends as a keyword to do so. Sometimes generic class acts like super-class or subclass. In Generic Hierarchy, All sub-classes move up any of the parameter types that are essential by super-class of generic in the hierarchy.

Can generic classes be inherited?

You cannot inherit a generic type. // class Derived20 : T {}// NO!


2 Answers

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.

like image 63
Bozho Avatar answered Oct 19 '22 03:10

Bozho


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)
like image 25
Eyal Schneider Avatar answered Oct 19 '22 03:10

Eyal Schneider