使用java反射获取类型的方法返回

时间:2017-02-16 03:53:06

标签: java methods reflection return-type

如果我有这样的课程:

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 ...

1 个答案:

答案 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());
            }
        }
    }
}
相关问题