Java 在切入点内获取带注释的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6604428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get annotated parameters inside a pointcut
提问by soldier.moth
I have two annotation @LookAtThisMethod
and @LookAtThisParameter
, if I have a pointcut around the methods with @LookAtThisMethod
how could I extract the parameters of said method which are annotated with @LookAtThisParameter
?
我有两个注解@LookAtThisMethod
和@LookAtThisParameter
,如果我身边有与方法的切入点@LookAtThisMethod
,我怎么能提取被标注了该方法的参数@LookAtThisParameter
?
For example:
例如:
@Aspect
public class LookAdvisor {
@Pointcut("@annotation(lookAtThisMethod)")
public void lookAtThisMethodPointcut(LookAtThisMethod lookAtThisMethod){}
@Around("lookAtThisMethodPointcut(lookAtThisMethod)")
public void lookAtThisMethod(ProceedingJoinPoint joinPoint, LookAtThisMethod lookAtThisMethod) throws Throwable {
for(Object argument : joinPoint.getArgs()) {
//I can get the parameter values here
}
//I can get the method signature with:
joinPoint.getSignature.toString();
//How do I get which parameters are annotated with @LookAtThisParameter?
}
}
采纳答案by soldier.moth
I modeled my solution around this other answerto a different but similar question.
我围绕这个不同但相似的问题的另一个答案模拟了我的解决方案。
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getMethod().getName();
Class<?>[] parameterTypes = signature.getMethod().getParameterTypes();
Annotation[][] annotations = joinPoint.getTarget().getClass().getMethod(methodName,parameterTypes).getParameterAnnotations();
The reason that I had to go through the target class was because the class that was annotated was an implementation of an interface and thusly signature.getMethod().getParameterAnnotations()
returned null.
我必须通过目标类的原因是因为被注释的类是一个接口的实现,因此signature.getMethod().getParameterAnnotations()
返回 null。
回答by kirenpillay
final String methodName = joinPoint.getSignature().getName();
final MethodSignature methodSignature = (MethodSignature) joinPoint
.getSignature();
Method method = methodSignature.getMethod();
GuiAudit annotation = null;
if (method.getDeclaringClass().isInterface()) {
method = joinPoint.getTarget().getClass()
.getDeclaredMethod(methodName, method.getParameterTypes());
annotation = method.getAnnotation(GuiAudit.class);
}
This code covers the case where the Method belongs to the interface
这段代码涵盖了Method属于接口的情况