public Interface Foo<T extends Colors>{...}
Is there a way to retrieve which T was given for an implementation of Foo?
For example,
public Class FooImpl implements Foo<Green>{..}
Would return Green.
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.
A Generic class can have muliple type parameters.
Using generics, primitive types can not be passed as type parameters. In the example given below, if we pass int primitive type to box class, then compiler will complain. To mitigate the same, we need to pass the Integer object instead of int primitive type.
Contrary to other answers, you can obtain the type of a generic parameter. For example, adding this to a method inside a generic class will obtain the first generic parameter of the class (T
in your case):
ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
type.getActualTypeArguments()[0]
I use this technique in a generic Hibernate DAO I wrote so I can obtain the actual class being persisted because it is needed by Hibernate. It works!
EDIT
Turns out for this case it is possible to get the generic information. Singleshot posted an answer which does just that. His should be the accepted answer. Re-qualifying mine.
In general though, there are many cases where you are unable to get type information you might expect to be there. Java uses a technique called type erasure which removes the types from the generic at compile time. This prevents you from getting information about their actual binding at runtime in many scenarios.
Nice FAQ on the subject:
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