2012-11-10 105 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

謝謝澄清。必須是程序員失敗的永久點。 ;-) –