访问返回类型的泛型参数

时间:2011-08-04 09:16:03

标签: java reflection

是否可以访问以下行中的泛型参数?

 public List<StoryLikeRef> getLikes() throws IOException

我的意思是通过反射从返回类型中获取StoryLikeRef?

由于

1 个答案:

答案 0 :(得分:10)

是的,您可以,假设StoryLikeRef是具体类型(而不是类型参数本身)。使用Method.getGenericReturnType获取Type。示例代码:

import java.lang.reflect.*;
import java.util.*;

public class Test {

    public List<String> getStringList() {
        return null;
    }

    public List<Integer> getIntegerList() {
        return null;
    }

    public static void main(String[] args) throws Exception {
        showTypeParameters("getStringList");
        showTypeParameters("getIntegerList");
    }

    // Only using throws Exception for sample code. Don't do
    // this in real life.
    private static void showTypeParameters(String methodName)
        throws Exception {
        Method method = Test.class.getMethod(methodName);
        Type returnType = method.getGenericReturnType();
        System.out.println("Overall return type: " + returnType);
        if (returnType instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) returnType;
            for (Type t: type.getActualTypeArguments()) {
                System.out.println("  Type parameter: " + t);
            }
        } else {
            System.out.println("Not a generic type");
        }
    }
}
相关问题