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.
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);
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.
You cannot inherit a generic type. // class Derived20 : T {}// NO!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With