如果我有这样的课程:
class Test {
Thing<String> getThing(String thing) {}
}
如何在Test实例上使用反射来确定String.class?
我想要的路径是新的Test() - &gt;得到课 - &gt;查找方法 - &gt;获取返回类型 - &gt; - &gt;不知何故得到String.class,但我没有找到最后一部分是如何完成的。到目前为止,我得到的是Thing<java.lang.String>
而不是内部阶级。
import org.reflections.ReflectionUtils;
Iterables.getOnlyElement(ReflectionUtils.getAllMethods((new Test()).getClass())).getGenericType();
而.getReturnType()
只给我一个Thing.class
...
答案 0 :(得分:1)
在Java中,您可以使用标准反射API(无需使用ReflectionUtils
)来获取它。您正确使用了getGenericReturnType
。您只需将其强制转换为ParameterizedType
:
public static void main(String[] args) throws NoSuchMethodException {
Method m = Test.class.getDeclaredMethod("getThing", String.class);
Type type = m.getGenericReturnType();
// type is Thing<java.lang.String>
if(type instanceof ParameterizedType) {
Type[] innerTypes = ((ParameterizedType) type).getActualTypeArguments();
if(innerTypes.length == 1) {
Type innerType = innerTypes[0];
if(innerType instanceof Class) {
// innerType is java.lang.String class
System.out.println(((Class<?>) innerType).getName());
}
}
}
}