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
}
getAnnotation(Annotation. class). param1() to get the param1 value. Here you have named your annotation interface as Annotation.
The isAnnotation() method is used to check whether a class object is an annotation. The isAnnotation() method has no parameters and returns a boolean value. If the return value is true , then the class object is an annotation. If the return value is false , then the class object is not an annotation.
A class parameter is simply an arbitrary name-value pair; you can use it to store any information you like about a class. To define a class-specific constant value. To provide parameterized values for method generator methods to use.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With