如何通过检查找到返回类型的参数化类型? [英] How to find the parameterized type of the return type through inspection?

查看:129
本文介绍了如何通过检查找到返回类型的参数化类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 方法[] allMethods =使用反射来获取所有类中的所有方法, c.getDeclaredMethods(); 

然后我遍历方法

< pre $ for(方法m:allMethods){
//我想知道返回值是否是参数化类型
m.getReturnType();
}

例如:如果我有这样一个方法:

  public Set< Cat> getCats()方法; 

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

解决方案

您是否尝试过 getGenericReturnType()


返回一个类型对象,它表示方法的正式返回类型用这个方法对象表示。如果返回类型是一个参数化类型,那么返回的类型对象必须准确地反映源代码中使用的实际类型参数。

如果返回类型是类型变量或参数化类型,则会创建它。否则,它已解决。

然后(从查看Javadocs),您似乎必须将它转换为 ParameterizedType 并调用< a href =http://java.sun.com/javase/6/docs/api/java/lang/reflect/ParameterizedType.html#getActualTypeArguments() =noreferrer> getActualTypeArguments( )



所以这是一些示例代码:

<$ (方法m:allMethods){
类型t = m.getGenericReturnType();
if(t instanceof ParameterizedType){
System.out.println(t); //java.util.Set< yourpackage.Cat>
for(类型arg:((ParameterizedType)t).getActualTypeArguments()){
System.out.println(arg); //class yourpackage.Cat
}
}
}


I am using reflection to get all the get all the methods in a class like this:

Method[] allMethods = c.getDeclaredMethods();

After that I am iterating through the methods

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

For example: if I have a method like this one:

public Set<Cat> getCats();

How can I use reflection to find out the return type contain Cat as the parameterized type?

解决方案

Have you tried 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.

Then (from looking at the Javadocs), it seems that you must cast it to ParameterizedType and call getActualTypeArguments() on it.

So here's some sample code:

    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"
            }
        }
    }

这篇关于如何通过检查找到返回类型的参数化类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆