payloc91
payloc91

Reputation: 3809

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...
    // for example here, method is an instance of myMethod in MyClass
}

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)` 

returns null, whereas MyClass is clearly annotated by @ClassAnnotation1.

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

Upvotes: 0

Views: 1104

Answers (1)

payloc91
payloc91

Reputation: 3809

You have to use method.getDeclaringClass().getAnnotation(ClassAnnotation1.class)


The fact that method.getParameters() returns the method's parameters, probably mislead you into thinking that method.getClass() returns the class containing your method.

Method::getClass() in fact returns Class<? extends Method>, which is clearly not annotated by @ClassAnnotation1. That's why you got null

Upvotes: 1

Related Questions