【问题标题】:How to check if a parameter of the current method has an annotation and retrieve that parameter value in Java?如何检查当前方法的参数是否具有注释并在 Java 中检索该参数值?
【发布时间】:2011-11-05 21:56:57
【问题描述】:

考虑这段代码:

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

【问题讨论】:

  • 我没看出你有什么问题
  • +1 不做new Exception().getStackTrace()

标签: java class reflection methods annotations


【解决方案1】:

外部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 包。不过,我不能告诉你太多。

【讨论】:

  • 是的,我想得到用@Foo注释的实际参数。
  • 您应该为此创建一个明确的问题,因为它会在(不相关的)注释内容之间丢失。
【解决方案2】:

getParameterAnnotations 返回一个长度等于方法参数数量的数组。该数组中的每个元素都在该参数上包含一个 annotations 数组。
所以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;
}

【讨论】:

    【解决方案3】:

    如果您要查找该方法的注释,您可能需要method.getAnnotations() 或method.getDeclaredAnnotations()。

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

    回头看问题标题,我怀疑您正在寻找参数的注释,而我没有在问题的内容中阅读。如果是这样,您的代码看起来不错。

    请参阅 Method Javadoc 和 AnnotatedElement Javadoc。

    【讨论】:

      猜你喜欢
      • 2014-05-21
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      相关资源
      最近更新 更多