hatboysam hatboysam - 1 year ago 65
Java Question

Reflection for Class of generic parameter in Java?

Imagine the following scenario:

class MyClass extends OtherClass<String>{

String myName;


class OtherClass<T> {

T myfield;


And I am analyzing MyClass using reflection specifically
, 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?


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.

Answer Source

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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download