我花了一段时间才弄清楚我在注释方法参数时没有犯错误。
但是我仍然不确定为什么,在下面的代码示例中,方式没有。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()
或者返回的类数组不包含参数注释是否有逻辑原因?