如何检查当前方法的参数是否有注释并在Java中检索该参数值?

时间:2011-08-29 09:54:53

标签: java class reflection methods annotations

考虑以下代码:

public example(String s, int i, @Foo Bar bar) {
  /* ... */
}

我想检查方法是否有注释@Foo并获取参数,如果没有找到@Foo注释则抛出异常。

我目前的方法是首先获取当前方法,然后遍历参数注释:

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实际返回的内容......

3 个答案:

答案 0 :(得分:6)

外部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)

进行注释

从你的问题来看,你想要做什么并不完全清楚。我们同意形式参数与实际参数的区别:

void foo(int x) { }

{ foo(3); }

其中x是参数而3是参数?

无法通过反射获取方法的参数。如果可能的话,您必须使用sun.unsafe包。我不能告诉你很多。

答案 1 :(得分:4)

getParameterAnnotations返回一个长度等于方法参数量的数组。该数组中的每个元素都包含该参数的annotations数组 因此getParameterAnnotations()[2][0]包含第三个([0])参数的第一个([2])注释。

如果您只需要检查至少一个参数是否包含特定类型的注释,该方法可能如下所示:

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;
}

答案 2 :(得分:3)

如果您正在寻找有关该方法的注释,您可能需要method.getAnnotations()method.getDeclaredAnnotations()

method.getParameterAnnotations()调用会为您提供有关方法形式参数的注释,而不是方法本身。

回顾问题标题,我怀疑你 正在寻找关于参数的注释,我没有在问题的内容中阅读。如果是这种情况,您的代码看起来很好。

请参阅Method JavadocAnnotatedElement Javadoc