How to find the parameterized type of the return t

2019-04-14 20:25发布

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条回答
一纸荒年 Trace。
2楼-- · 2019-04-14 21:15

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"
            }
        }
    }
查看更多
登录 后发表回答