Get parameter value if parameter annotation exists

13,951

Solution 1

In your doIntercept() you can retrieve the method being called from the InvocationContext and get the parameter annotations.

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]);

Because the Annotation[][] returns an empty 2nd dimension array if there are no Annotations, you know which parameter positions have the annotations. You can then call InvocationContext#getParameters() to get a Object[] with the values of all the parameters passed. The size of this array and the Annotation[][] will be the same. Just return the value of the indices where there are no annotations.

Solution 2

You can try something like this,I define a Param annotation named MyAnnotation and I get the Param annotation in this way. It works.

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

Solution 3

You can try something like this

    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)
        }
    }
Share:
13,951
user2664820
Author by

user2664820

Updated on July 29, 2022

Comments

  • user2664820
    user2664820 almost 2 years

    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
    }