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 に答える