Unfortunately, it's not a field - it's a method's return type.
No problem, as long as the genericity is defined in the class. Example:
import java.util.*;
import java.lang.reflect.*;
public class ReflectMethodGenerics {
public static void main(String[] args) throws Exception {
ReflectMethodGenerics rg = new ReflectMethodGenerics();
Class c = rg.getClass();
Method m = c.getMethod("GenericMethod");
Type t = m.getGenericReturnType();
Class x = extractType(t);
System.out.println(x);
}
public ArrayList<String> GenericMethod() {
ArrayList<String> s = new ArrayList<String>();
return s;
}
private static Class extractType(Type t) {
if (t != null && t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) t;
Type[] genTypes = pt.getActualTypeArguments();
if (genTypes.length == 1 && genTypes[0] instanceof Class) {
return (Class) genTypes[0];
} else if (genTypes.length == 2 && genTypes[1] instanceof Class)
{
// TODO we might want to store the index type at some point
return (Class) genTypes[1];
}
}
return null;
}
}
-------------------------
However, if the method's return type isn't declared as the generic type, you
can't get the parameterized type, as this also is valid...
public ArrayList GenericMethod() {
ArrayList<String> s = new ArrayList<String>();
return s;
}
// Bjorn A