Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics - upper bounds in method signature [duplicate]

Tags:

java

generics

I have a method where I want to accept class types that must extend an abstract class. What is the difference between

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

and

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

I wouldn't be able to directly reference the type inside the method in the second case. Is there any difference in which class types could be passed to these two methods?

like image 535
joeblubaugh Avatar asked Apr 20 '15 18:04

joeblubaugh


People also ask

What is upper bounded wildcards in generics?

You can use an upper bounded wildcard to relax the restrictions on a variable. For example, say you want to write a method that works on List<Integer>, List<Double>, and List<Number>; you can achieve this by using an upper bounded wildcard.

How are bounds used with generics?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.

How do you declare a generic bounded type parameter in Java?

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).


2 Answers

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

like image 198
John Bollinger Avatar answered Oct 07 '22 21:10

John Bollinger


In the 1st one you will also be able to return T (or any type parameterized with T: List<T>, Set<T> and so on...) , without needing to cast it

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

And use it as :

Subclass parameterInstance =... 
Subclass i1 = myMethod(parameterInstance.getClass());
like image 32
Yosef-at-Panaya Avatar answered Oct 07 '22 22:10

Yosef-at-Panaya