I have a program written in Java 11 with two custom annotation. One on Method level and one on Parameter level. I`m using Spring AOP to act on methods that use my Custom annotations. But I have not found a way to get the value ouf of an optional annotation that is on Parameter level.
@CustomAnnotation
public void myMethod(@CustomValue String param1, int param2) {
...
}
@AfterReturning(value = "@annotation(customAnnotation)", argNames = "customAnnotation, jp")
public void afterReturning(JoinPoint jp, CustomAnnotation customAnnotation) {
...
}
The program works well with my @CustomAnnotation, but I have problems to get the value out of parameters that is annotated with @CustomValue. @CustomValue is useless if the method is not annotated with @CustomAnnotation. And the number of parameters that can be annotated with @CustomValue is 0 or more.
How can I get the values from the parameters that is annotated with @CustomValue on a method that is annotated with @CustomAnnotation?
CodePudding user response:
@AfterReturning(value = "@annotation(CustomAnnotation)", argNames = "customAnnotation, jp")
public void afterReturning(JoinPoint jp, CustomAnnotation customAnnotation) {
CustomAnnotation annotation = customAnnotation;
List<Parameter> parameterList = new ArrayList<>();
if (jp.getSignature() instanceof MethodSignature) {
MethodSignature signature =
(MethodSignature) jp.getSignature();
Method method = signature.getMethod();
anno = method.getAnnotation(CustomAnnotation.class);
Parameter[] params = method.getParameters();
for (Parameter param : params) {
try {
if(param.getAnnotation(CustomValue.class) !=null){
parameterList.add(param);
}
} catch (Exception e) {
//do nothing
}
}
}
}
You should now get the list of parameters annotated with @CustomValue. This exact code may not work while copy-paste, but you should get the idea.
CodePudding user response:
Maybe there is a better way, but I solved this by using following:
@AfterReturning(value = "@annotation(customAnnotation)", argNames = "customAnnotation, jp")
public void afterReturning(JoinPoint jp, CustomAnnotation customAnnotation) {
MethodSignature signature = (MethodSignature) jp.getSignature();
Parameter[] parameters = signature.getMethod().getParameters();
Object[] args = jp.getArgs();
for (int i = 0; i < args.length; i) {
if (parameters[i].isAnnotationPresent(CustomValue.class)) {
Object paramValue = args[i];
}
}
}