Reputation: 490
I want to analysis the declared field variable in class MyComponent
, and I want to get the GenericDeclartion's type of the field class, not the type it's declared in MyComponent
. The demo is below.
public class SomeConfig<OP extends Operation> {
private OP operation;
public SomeConfig(OP op) {
this.operation = op;
}
}
public class MyComponent {
private SomeConfig<?> config;
public MyComponent(SomeConfig<?> config) {
this.config = config;
}
}
public class MyAnalysis {
public static void main(String[] args) {
Class clazz = MyComponent.class;
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
Type type = f.getGenericType();
if(type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType)type;
System.out.println(pType.getActualTypeArguments()[0]); // which prints "?" for sure
}
}
}
}
The Problem: The printed result is "?" for sure. But all I want is to get the type of Operation
to be printed instead of "?". Is it achievable?
Upvotes: 0
Views: 75
Reputation: 131526
But all I want is to get the type of Operation
Generics are erased after compilation, so you could not access to them in this way at runtime.
To achieve your need, you could change the SomeConfig
constructor in order to pass the class instance of the parameterized type :
public class SomeConfig<OP extends Operation> {
private OP operation;
private Class<OP> clazz;
public SomeConfig(OP op, Class<OP> clazz) {
this.operation = op;
this.clazz = clazz;
}
}
Now the clazz
field may be used to know the class of the type.
Upvotes: 3