2012-11-10 130 views
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中的注释imnplementation一个缺陷? 或者有没有逻辑的原因,为什么Method.getParameterTypes()返回的类数组不包含参数注释?

回答

4

这不是实施中的缺陷。

Method#getParameterTypes()的调用返回参数类型的数组,这意味着它们的类。当您获得该类的注释时,您将得到String的注释,而不是方法参数本身,而String没有注释(view source)。

+0

谢谢澄清。必须是程序员失败的永久点。 ;-) –