是否可以在下一行中访问通用参数?

 public List<StoryLikeRef> getLikes() throws IOException


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

谢谢

最佳答案

是的,您可以假设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");
        }
    }
}

09-27 07:04