访问返回类型的泛型参数

Rom*_*man 2 java reflection

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

 public List<StoryLikeRef> getLikes() throws IOException
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Jon*_*eet 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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)