Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 315
user2664820 Avatar asked Aug 08 '13 14:08

user2664820


People also ask

How do you find the parameters of annotations?

getAnnotation(Annotation. class). param1() to get the param1 value. Here you have named your annotation interface as Annotation.

How do you check if a method has an 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.

What is class parameter in Java?

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.


1 Answers

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.

like image 63
Sotirios Delimanolis Avatar answered Nov 08 '22 14:11

Sotirios Delimanolis