メソッドのパラメーターにアノテーションを付けたのが間違いではないことを理解するのにしばらく時間がかかりました。
しかし、次のコード例では、なぜいいえなのか、まだわかりません。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()
または、によって返されるクラス配列がパラメーター注釈を保持しない論理的な理由はありますか?