How to find the parameterized type of the return type through inspection?

我只是一个虾纸丫 提交于 2020-01-01 18:18:21

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/1213735/how-to-find-the-parameterized-type-of-the-return-type-through-inspection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!