如何检查当前方法的参数是否有注释并在Java中检索该参数值?
考虑以下代码:
public example(String s, int i, @Foo Bar bar) { /* ... */ }
我想检查方法是否有注释@Foo
并获取参数或如果没有找到@Foo
注释则抛出exception。
我目前的方法是首先获取当前方法,然后遍历参数注释:
import java.lang.annotation.Annotation; import java.lang.reflect.Method; class Util { private Method getCurrentMethod() { try { final StackTraceElement[] stes = Thread.currentThread().getStackTrace(); final StackTraceElement ste = stes[stes.length - 1]; final String methodName = ste.getMethodName(); final String className = ste.getClassName(); final Class currentClass = Class.forName(className); return currentClass.getDeclaredMethod(methodName); } catch (Exception cause) { throw new UnsupportedOperationException(cause); } } private Object getArgumentFromMethodWithAnnotation(Method method, Class annotation) { final Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (Annotation[] annotations : paramAnnotations) { for (Annotation an : annotations) { /* ... */ } } } }
这是正确的方法还是有更好的方法? forach循环中的代码如何? 我不确定我是否理解了getParameterAnnotations
实际返回的内容……
外部for循环
for (Annotation[] annotations : paramAnnotations) { ... }
应该使用显式计数器,否则你不知道你现在正在处理什么参数
final Annotation[][] paramAnnotations = method.getParameterAnnotations(); final Class[] paramTypes = method.getParameterTypes(); for (int i = 0; i < paramAnnotations.length; i++) { for (Annotation a: paramAnnotations[i]) { if (a instanceof Foo) { System.out.println(String.format("parameter %d with type %s is annotated with @Foo", i, paramTypes[i]); } } }
还要确保使用@Retention(RetentionPolicy.RUNTIME)
注释注释类型
从你的问题来看,你想要做的事情并不完全清楚。 我们同意forms参数与实际参数的区别:
void foo(int x) { } { foo(3); }
其中x
是参数, 3
是参数?
通过reflection得到方法的参数是不可能的。 如果可以的话,你必须使用sun.unsafe
包。 虽然我不能告诉你太多。
getParameterAnnotations
返回一个数组,其长度等于方法参数的数量。 该数组中的每个元素都包含该参数的注释数组。
因此getParameterAnnotations()[2][0]
包含第三个( [2]
)参数的第一个( [0]
)注释。
如果您只需要检查至少一个参数是否包含特定类型的注释,则该方法可能如下所示:
private boolean isAnyParameterAnnotated(Method method, Class> annotationType) { final Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (Annotation[] annotations : paramAnnotations) { for (Annotation an : annotations) { if(an.annotationType().equals(annotationType)) { return true; } } } return false; }
如果您正在寻找方法的注释,您可能需要method.getAnnotations()
或method.getDeclaredAnnotations()
。
method.getParameterAnnotations()
调用为您提供了方法的forms参数的注释,而不是方法本身。
回顾问题标题,我怀疑你正在寻找关于参数的注释,我没有在问题的内容中阅读。 如果是这种情况,您的代码看起来很好。
请参见方法Javadoc和AnnotatedElement Javadoc 。