简体   繁体   中英

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

I want to analysis the declared field variable in class MyComponent , and I want to get the GenericDeclartion's type of the field class, not the type it's declared in MyComponent . The demo is below.

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
            }
        }
    }
}

The Problem: The printed result is "?" for sure. But all I want is to get the type of Operation to be printed instead of "?". Is it achievable?

But all I want is to get the type of Operation

Generics are erased after compilation, so you could not access to them in this way at runtime.

To achieve your need, you could change the SomeConfig constructor in order to pass the class instance of the parameterized type :

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

Now the clazz field may be used to know the class of the type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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