user755806 user755806 - 1 month ago 6
Java Question

How to get a method's annotation value from a ProceedingJoinPoint?

I have below annotation.

MyAnnotation.java



@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

}


SomeAspect.java



public class SomeAspect{

@Around("execution(public * *(..)) && @annotation(com.mycompany.MyAnnotation)")
public Object procede(ProceedingJoinPoint call) throws Throwable {

//Some logic

}

}


SomeOther.java



public class SomeOther{

@MyAnnotation("ABC")
public String someMethod(String name){


}


}


In above class am passing "ABC" with in @MyAnnotation.
Now how can i access "ABC" value in procede method of SomeAspect.java class?

Thanks!

Answer

You can get the Signature from a ProceedingJoinPoint and in case of a method invocation just cast it to a MethodSignature.

@Around("execution(public * *(..)) && @annotation(com.mycompany.MyAnnotation)")
public Object procede(ProceedingJoinPoint call) throws Throwable {
    MethodSignature signature = (MethodSignature) call.getSignature();
    Method method = signature.getMethod();

    MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
}

But you should first add an annotation attribute. Your example code doesn't have one, e.g.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

    String value();
}

Then you can access it

MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
String value = myAnnotation.value();