Search code examples
javareflectionannotationsejbinterceptor

Get parameter value if parameter annotation exists


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
}

Solution

  • 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();
    Object[] parameterValues = context.getParameters();
    
    // then iterate through parameters and check if annotation exists at each index, example with first parameter at index 0:
    if (annotations[0].length > 0 /* and add check 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.