Udo Klimaschewski
Udo Klimaschewski

Reputation: 5315

Method parameter annotations access

It took me a while to figure out that I was not making a mistake in annotating my method parameters.
But I am still not sure why, in the following code example, the way no. 1 does not work:

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

public class AnnotationTest {

    @Retention(RetentionPolicy.RUNTIME)
    @interface MyAnnotation {
        String name() default "";
        }

    public void myMethod(@MyAnnotation(name = "test") String st) {

    }

    public static void main(String[] args) throws NoSuchMethodException, SecurityException {
        Class<AnnotationTest> clazz = AnnotationTest.class;
        Method method = clazz.getMethod("myMethod", String.class);

        /* Way no. 1 does not work*/
        Class<?> c1 = method.getParameterTypes()[0];
        MyAnnotation myAnnotation = c1.getAnnotation(MyAnnotation.class);
        System.out.println("1) " + method.getName() + ":" + myAnnotation);

        /* Way no. 2 works */
        Annotation[][] paramAnnotations = method.getParameterAnnotations();
        System.out.println("2) " + method.getName() + ":" + paramAnnotations[0][0]);
    }

}

Output:

    1) myMethod:null
    2) myMethod:@AnnotationTest$MyAnnotation(name=test)

Is it just a flaw in the annotation imnplementation in Java? Or is there a logical reason why the class array returned by Method.getParameterTypes() does not hold the parameter annotations?

Upvotes: 2

Views: 11546

Answers (1)

FThompson
FThompson

Reputation: 28687

This is not a flaw in the implementation.

A call to Method#getParameterTypes() returns an array of the parameters' types, meaning their classes. When you get the annotation of that class, you are getting the annotation of String rather than of the method parameter itself, and String has no annotations (view source).

Upvotes: 4

Related Questions