I'm looking to access the generic type of a declared field during runtime. I was previously under the impression that this was not possible due to the Java type erasure. However, this must not be the case because some well known frameworks leverage the generic type through reflection during runtime.
As an example, Guice will implement a Provider based upon the generic type you provide:
public class Injectable{
@Inject
private Provider<SomeType> someTypeProvider;
}
How does one access the 'SomeType' generic attribute of a field or any such type/method/etc through the reflection API?
Additionally it would be helpful to also know how to access these generic type attributes through the Java 6 Annotation Processor API.
Thanks.
Edit:
Thank you all for your great pointers. I found a way to do this using haylem's links, specifically the one to Prenkov's article Java Reflection: Generics.
Here's the answer I was looking for:
/**
* @author John Ericksen
*/
public class TypeReflectionExample {
public class SomeType{}
public class Injectable{
@Inject private Provider<SomeType> someTypeProvider;
}
public static void main(String[] args){
try {
Field providerField = Injectable.class.getDeclaredField("someTypeProvider");
Type genericFieldType = providerField.getGenericType();
if(genericFieldType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericFieldType;
Type[] fieldArgTypes = aType.getActualTypeArguments();
for(Type fieldArgType : fieldArgTypes){
Class fieldArgClass = (Class) fieldArgType;
System.out.println("fieldArgClass = " + fieldArgClass);
}
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
results in:
fieldArgClass = class test.TypeReflectionExample$SomeType
The same can be done for Methods, Constructors, Superclass extensions/implements, etc
I'm awarding haylem, as his post led me to this solution, even if it didn't directly answer my question.
It is true that generics aren't generally known at runtime in Java, because they are implemented with Type Erasure.
However, you can stil extract some valuable information about the declared types (NOT the runtime objects' types), as presented in Ian Roberston's article Reflecting Generics and Prenkov's article Java Reflection: Generics.
Generics where introduced while conserving backwards compatibility at the source qnd binary level, hence some of their limitation, like:
<>
),