mercredi 29 novembre 2017

How do I get class annotations from a Method instance?

Consider the following class:

@ClassAnnotation1
@ClassAnnotation2
class MyClass {

    // ...        

    @MethodAnnotation1
    @MethodAnnotation2
    private void myMethod(@ParamAnnotation1 @ParamAnnotation2 int i) {
    // ...
    }
}

During a reflection phase of my application, I need to analyze various code aspects, given a Method instance.

public void analyze(final Method method) {
    // do the analysis...
}

I can easily analyze the parameters' Annotation by doing

for (Parameter p : method.getParameters()) {
    if (p.getAnnotation(ParamAnnotation1.class) != null) {
        // ...
    }
}

and get the results I expect.

The method's Annotation's can easily be processed with

method.getAnnotation(MethodAnnotation1.class)


Unfortunately I fail to get the expected results for the class' Annotation's.

In fact, the call to method.getClass().getAnnotation(ClassAnnotation1.class) return null, whereas MyClass is clearly annotated by @ClassAnnotation1.

How do I get the MyClass annotations from a Method instance?





Aucun commentaire:

Enregistrer un commentaire