dimanche 18 juin 2017

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?





Aucun commentaire:

Enregistrer un commentaire