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.
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.
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:
[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
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;
}
}
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!
Depends on what you mean exactly.
Just T
might be what you want, for example:
public Interface Foo<T extends Colors>{ public T returnType() {...} ...}
There's. Look at Javadoc for java.lang.Class#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);
}
}