Java generics - retrieve type
public Interface Fo开发者_JAVA百科o<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.
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:
- http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html#Reflection
There's. Look at [Javadoc for java.lang.Class#getGenericInterfaces()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getGenericInterfaces()).
Like this:
public class Test1 {
interface GenericOne<T> {
}
public class Impl implements GenericOne<Long> {
}
public static void main(String[] argv) {
Class c = (Class) ((ParameterizedType) Impl.class.getGenericInterfaces()[0]).getActualTypeArguments()[0];
System.out.println(c);
}
}
One way to do this is to explicitly pass in a Class object with the type. Something like the following:
public class FooImpl<T extends Colors> {
private Class<T> colorClass;
public FooImpl(T colorClass) {
this.colorClass = colorClass;
}
public Class<T> getColorClass() {
return colorClass;
}
}
Depends on what you mean exactly.
Just T
might be what you want, for example:
public Interface Foo<T extends Colors>{ public T returnType() {...} ...}
[edit] Ok, apparently partially possible. Good explanation of how to do it, (including an improvement upon the method posted by SingleShot): http://www.artima.com/weblogs/viewpost.jsp?thread=208860
精彩评论