繁体   English   中英

如何使用Java Reflection从ParameterizedType获取GenericDeclaration的类型?

[英]How to get the Type of GenericDeclaration from ParameterizedType using Java Reflection?

我想分析MyComponent类中声明的字段变量,并且想要获得GenericDeclartion字段类的类型,而不是它在MyComponent声明的类型。 该演示如下。

public class SomeConfig<OP extends Operation> {
    private OP operation;

    public SomeConfig(OP op) {
        this.operation = op;
    }
}

public class MyComponent {
    private SomeConfig<?> config;

    public MyComponent(SomeConfig<?> config) {
        this.config = config;
    }
}

public class MyAnalysis {
    public static void main(String[] args) {
        Class clazz = MyComponent.class;
        Field[] fields = clazz.getDeclaredFields();
        for (Field f : fields) {
            Type type = f.getGenericType();
            if(type instanceof ParameterizedType) {
                 ParameterizedType pType = (ParameterizedType)type;
                 System.out.println(pType.getActualTypeArguments()[0]); // which prints "?" for sure
            }
        }
    }
}

问题:打印结果是“?” 当然。 但是,我要获取的是要打印的Operation类型,而不是“?”。 可以实现吗?

但是我想要的就是获取操作类型

泛型在编译后会被擦除,因此您无法在运行时以这种方式访问​​它们。

为了满足您的需求,您可以更改SomeConfig构造函数以传递参数化类型的类实例:

public class SomeConfig<OP extends Operation> {
    private OP operation;
    private Class<OP> clazz;

    public SomeConfig(OP op, Class<OP> clazz) {
      this.operation = op;
      this.clazz = clazz;
    }
}

现在, clazz字段可用于了解类型的类别。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM