java - 如何通过检查找到返回类型的参数化类型?

标签 java generics reflection

我正在使用反射来获取类中的所有方法,如下所示:

Method[] allMethods = c.getDeclaredMethods();

之后我将迭代这些方法

for (Method m: allMethods){
    //I want to find out if the return is is a parameterized type or not
    m.getReturnType();
}

例如:如果我有这样的方法:

public Set<Cat> getCats();

如何使用反射来找出包含 Cat 作为参数化类型的返回类型?

最佳答案

你试过吗getGenericReturnType()

Returns a Type object that represents the formal return type of the method represented by this Method object.

If the return type is a parameterized type, the Type object returned must accurately reflect the actual type parameters used in the source code.

If the return type is a type variable or a parameterized type, it is created. Otherwise, it is resolved.

然后(从Javadocs来看),似乎你必须将其转换为 ParameterizedType并调用getActualTypeArguments()就在上面。

这里是一些示例代码:

    for (Method m : allMethods) {
        Type t = m.getGenericReturnType();
        if (t instanceof ParameterizedType) {
            System.out.println(t);       // "java.util.Set<yourpackage.Cat>"
            for (Type arg : ((ParameterizedType)t).getActualTypeArguments()) {
                System.out.println(arg); // "class yourpackage.Cat"
            }
        }
    }

关于java - 如何通过检查找到返回类型的参数化类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1213735/

相关文章:

c# - 有没有一种类型化的方法来在 C# 中声明方法名称

c - 非动态加载代码的类似 dlsym 的功能?

java - XML 解析错误

java - Android - SimpleXML 框架无法解析@ElementList

java - 加法、减法和乘法需要数学上下文吗?

c# - 绑定(bind)泛型方法委托(delegate)时出错 - 签名或安全透明度

java - Spring Boot 加载 orm.xml

java - 在 Java 中转换迭代器类型

c# - 存储类型引用的强类型方式

来自规范名称的 java.lang.reflect.Type