varun
varun

Reputation: 726

Multiple, annotated parameter values in advice

How can i get the value of annotated parameters in my advice. I have a scenario like following:

@Custom
public void xxxx(@Param("a1") Object a, @Param("a2") Object b)
{
    //TODO
}

I want the pointcut to be defined for all methods having @Custom annotation, nothing fancy here. The problem is I want to get parameters marked with @Param and the value of annotations itself in advice. The number of such annotated parameters is not fixed, there could be any number or none at all.

So far I have used reflection and i am able the get parameters marked with annotation but not the value of annotation.

Upvotes: 0

Views: 335

Answers (1)

Adrian Adamczyk
Adrian Adamczyk

Reputation: 3070

This is how I get value of annotations:

My annotation is @Name:

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.PARAMETER)
@interface Name {
    String value();
}

And there's code responsible for getting it:

Annotation[][] parametersAnnotations = method.getParameterAnnotations();

for (int i = 0; i < parametersAnnotations.length; i++) {
    Annotation[] parameterAnnotations = parametersAnnotations[i];
    Annotation nameAnnotation = null;

    for (Annotation annotation : parameterAnnotations) {
        if (annotation.annotationType().equals(Name.class)) {
            nameAnnotation = annotation;
            break;
        }
    }

    if (nameAnnotation != null) {
        String textInAnnotation = ((Name)nameAnnotation).value();
    }
}

Upvotes: 1

Related Questions