Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics - retrieve type

Tags:

java

generics

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.

like image 221
tinkertime Avatar asked Nov 03 '09 20:11

tinkertime


People also ask

How can you bound generic types?

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.

Can generics take multiple type parameters?

A Generic class can have muliple type parameters.

Can generics be used for primitive types?

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.


2 Answers

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!

like image 187
SingleShot Avatar answered Sep 17 '22 18:09

SingleShot


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:

  • http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html#Reflection
like image 33
JaredPar Avatar answered Sep 18 '22 18:09

JaredPar