2

我花了一段时间才弄清楚我在注释方法参数时没有犯错误。
但是我仍然不确定为什么,在下面的代码示例中,方式没有。1不起作用:

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]);
    }

}

输出:

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

它只是Java注释实现中的一个缺陷吗?Method.getParameterTypes()或者返回的类数组不包含参数注释是否有逻辑原因?

4

1 回答 1

4

这不是实施中的缺陷。

调用Method#getParameterTypes()返回参数类型的数组,即它们的类。当您获得该类的注释时,您将获得的注释String而不是方法参数本身的注释,并且String没有注释(查看源代码)。

于 2012-11-10T19:32:59.937 回答