java 方法参数注解访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13325319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method parameter annotations access
提问by Udo Klimaschewski
It took me a while to figure out that I was not making a mistake in annotating my method parameters.
But I am still not sure why, in the following code example, the way no. 1 does not work:
我花了一段时间才弄清楚我在注释我的方法参数时没有犯错误。
但我仍然不确定为什么,在下面的代码示例中,没有。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]);
}
}
Output:
输出:
1) myMethod:null
2) myMethod:@AnnotationTest$MyAnnotation(name=test)
Is it just a flaw in the annotation imnplementation in Java?
Or is there a logical reason why the class array returned by Method.getParameterTypes()
does not hold the parameter annotations?
这只是Java中注释实现的一个缺陷吗?或者返回的类数组Method.getParameterTypes()
不包含参数注释是否存在合乎逻辑的原因?
回答by FThompson
This is not a flaw in the implementation.
这不是实施中的缺陷。
A call to Method#getParameterTypes()
returns an array of the parameters' types, meaning their classes. When you get the annotation of that class, you are getting the annotation of String
rather than of the method parameter itself, and String
has no annotations (view source).
调用Method#getParameterTypes()
返回参数类型的数组,即它们的类。当您获得该类的注释时,您获得的是 的注释String
而不是方法参数本身的String
注释,并且没有注释(查看源代码)。