class A<Type>{
private Type id;
}
class B extends A<String>{
}
B b = new B();
Field idField = //reflection code to get id field
How from "idField" , we can get the exact type of idField , means String instead of Type ?
class A<Type>{
private Type id;
}
class B extends A<String>{
}
B b = new B();
Field idField = //reflection code to get id field
How from "idField" , we can get the exact type of idField , means String instead of Type ?
I'm not exactly sure what you are trying to achieve. But I'm guessing that you would like to determine the concrete type of field 'id'.
public class A<T>{
public T id;
public Class<T> idType;
public A(){
idType = (Class<T>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
}
public class B extends A<String>{
}
public static void main(String[] args) throws Exception {
B b = new B();
System.out.println(b.idType);
}
The last sysout statement in the above code snippet will print 'java.lang.String'.
This is a technique that is very commonly used when writing generic functionality in the base class.