6

Is it possible to get the value of a parameter if an annotation is present on that parameter?

Given EJB with parameter-level annotations:

public void fooBar(@Foo String a, String b, @Foo String c) {...}

And an interceptor:

@AroundInvoke
public Object doIntercept(InvocationContext context) throws Exception {
    // Get value of parameters that have annotation @Foo
}
4

3 回答 3

7

在您的doIntercept()中,您可以检索从中调用的方法InvocationContext并获取参数注释

Method method = context.getMethod();
Annotation[][] annotations = method.getParameterAnnotations();
// iterate through annotations and check 
Object[] parameterValues = context.getParameters();

// check if annotation exists at each index
if (annotation[0].length > 0 /* and if the annotation is the type you want */ ) 
    // get the value of the parameter
    System.out.println(parameterValues[0]);

因为Annotation[][]如果没有注释,则返回一个空的二维数组,因此您知道哪些参数位置具有注释。然后,您可以调用InvocationContext#getParameters()以获取Object[]传递的所有参数的值。这个数组的大小和Annotation[][]将是一样的。只需返回没有注释的索引值。

于 2013-08-08T15:01:13.023 回答
4

您可以尝试这样的事情,我定义了一个名为 MyAnnotation 的 Param 注释,并以这种方式获得了 Param 注释。有用。

Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Class[] parameterTypes = method.getParameterTypes();

int i=0;
for(Annotation[] annotations : parameterAnnotations){
  Class parameterType = parameterTypes[i++];

  for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("param: " + parameterType.getName());
        System.out.println("value: " + myAnnotation.value());
    }
  }
}
于 2016-11-03T07:37:12.837 回答
1

你可以试试这样的

    Method m = context.getMethod();
    Object[] params = context.getParameters();
    Annotation[][] a = m.getParameterAnnotations();
    for(int i = 0; i < a.length; i++) {
        if (a[i].length > 0) {
            // this param has annotation(s)
        }
    }
于 2013-08-08T15:06:26.373 回答