Java Generics - upper bounds in method signature

I have a method in which I want to accept class types that should extend an abstract class. What's the difference between

<T extends AbstractClass> void myMethod(Class<T> clazz);

and

void myMethod(Class<? extends AbstractClass> clazz); ?

I could not directly refer to the type inside the method in the second case. Is there a difference in what types of classes can be passed to these two methods?

+7
java generics
source share
3 answers

No, there is no difference between argument types that are compatible with the two method signatures that you presented. Personally, I would use a parameterized version if I needed to refer to the exact type represented by the argument, but otherwise I would use a wildcard version.

+5
source share

In the first one, you can also return T (or any type parameterized with T: List <T>, Set <T>, etc.), without the need to use it

 <T extends AbstractClass> T myMethod(Class<T> clazz); 

And use it like:

 Subclass parameterInstance =... Subclass i1 = myMethod(parameterInstance.getClass()); 
+2
source share

This question has been asked in many places, in particular here and here .

Both questions relate primarily to unlimited wildcards and generic types, but the same principles apply here. I would also recommend reading one of the links (Angelika Langer - Java Generics Frequently Asked Questions) provided by one of the answers to other questions (posted here for convenience).

While in your particular case there is no difference, the difference boils down to how you deal with data of the type inside (inside the method). Go with what seems to best describe your purpose. If you are dealing with data of an unknown type, and you need a specific input type that can be specifically used in this method, you will need to use a general approach. If, on the other hand, you are missing and it might be enough to process all the input as just a limiting type (for example, AbstractClass in your case), you can go with a limited wildcard approach.

+1
source share

All Articles