如何从ProceedingJoinPoint获取方法的注释值? [英] How to get a method's annotation value from a ProceedingJoinPoint?
问题描述
我有以下注释。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
SomeAspect.java
SomeAspect.java
public class SomeAspect{
@Around("execution(public * *(..)) && @annotation(com.mycompany.MyAnnotation)")
public Object procede(ProceedingJoinPoint call) throws Throwable {
//Some logic
}
}
SomeOther.java
SomeOther.java
public class SomeOther{
@MyAnnotation("ABC")
public String someMethod(String name){
}
}
在上面的课程中,我在 @MyAnnotation 中传递 ABC 。
现在我如何在 SomeAspect.java 类的 procede 方法中访问 ABC 值?
In above class am passing "ABC" with in @MyAnnotation. Now how can i access "ABC" value in procede method of SomeAspect.java class?
谢谢!
推荐答案
你可以得到签名。 org / aspectj / doc / released / runtime-api / org / aspectj / lang / ProceedingJoinPoint.htmlrel =noreferrer> ProceedingJoinPoint ,如果是方法调用,只需将其转换为 MethodSignature 。
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);
}
但您应首先添加注释属性。您的示例代码没有,例如</ p>
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();
}
然后你可以访问它
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
String value = myAnnotation.value();
编辑
如果我在课程级别拥有@MyAnnotation(ABC),如何获得价值?
How to get value if I have @MyAnnotation("ABC") at class level ?
Class
也是 AnnotatedElement
,因此您可以使用与方法
。例如。可以使用
A Class
is also an AnnotatedElement
, so you can get it the same way as from a Method
. E.g. An annotation of the method's declaring class can be obtained using
Method method = ...;
Class<?> declaringClass = method.getDeclaringClass();
MyAnnotation myAnnotation = declaringClass.getAnnotation(MyAnnotation.class)
这篇关于如何从ProceedingJoinPoint获取方法的注释值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!