user2664820 user2664820 - 1 month ago 18
Java Question

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
}

Answer

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.