Method parameter annotations access

11,392

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

Share:
11,392
Udo Klimaschewski
Author by

Udo Klimaschewski

Been there, done that. Links: about.me LinkedIn Twitter Facebook The proud owner of UdoJava.com and Apparillos.com

Updated on June 04, 2022

Comments

  • Udo Klimaschewski
    Udo Klimaschewski almost 2 years

    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?

  • Udo Klimaschewski
    Udo Klimaschewski over 11 years
    Thank you for clarification. Must be a permanent point of programmers failure. ;-)