Imagine the following scenario:
class MyClass extends OtherClass<String>{
String myName;
//Whatever
}
class OtherClass<T> {
T myfield;
}
And I am analyzing MyClass using reflection specifically (MyClass.class).getDeclaredFields()
, in this case I will get the following fields (and Types, using getType() of the Field):
myName --> String
myField --> T
I want to get the actual Type for T, which is known at runtime due to the explicit "String" in the extends notation, how do I go about getting the non-genetic type of myField?
EDIT RESOLVED:
Seems like the answer is "you can't". For those who may look at this question later I'd recommend using Jackson (I was trying to do this to generate JSON) and annotating your classes and fields in such a way so that Jackson is aware of the inheritance hierarchy and can automatically do what the correct answer below suggested.
This can be achieved with reflection only because you explicitly used String
, otherwise this information would've been lost due to type erasure.
ParameterizedType t = (ParameterizedType) MyClass.class.getGenericSuperclass(); // OtherClass<String>
Class<?> clazz = (Class<?>) t.getActualTypeArguments()[0]; // Class<String>