java - 访问返回类型的泛型参数

标签 java reflection

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

 public List<StoryLikeRef> getLikes() throws IOException

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

谢谢

最佳答案

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

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

关于java - 访问返回类型的泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6938858/

相关文章:

c# - 为什么 MethodImplAttributes 没有标记 FlagsAttribute?

java - 获取高阶函数中函数参数的名称

java - 从 CSV 文件中获取随机元素

java - 对象被标记为 "javax.validation.constraints.NotNull"但未在此构造函数中初始化

java - 您可以使用 java.util.Random 找到以前生成的随机数吗?

java.lang.NoSuchMethodError : com. google.common.base.CharMatcher.ascii() 错误

swift - 是否有与 C#'s ' nameof( )' function to get a variable or member' s name?

java - 如何在java中使用jFileChooser的打开按钮?

java - BO <=> Java 中的 DTO 映射器

java - 有没有办法在Java中获取方法参数的名称?