2011-07-07 11 views
13

我有兩個註釋@LookAtThisMethod@LookAtThisParameter,如果我對@LookAtThisMethod方法有切入點,我怎樣才能提取用@LookAtThisParameter註解的方法的參數?獲取切入點內的註釋參數

例如:

@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? 
    } 

} 

回答

29

我模仿我的這個other answer圍繞解決了不同但類似的問題。

MethodSignature signature = (MethodSignature) joinPoint.getSignature(); 
String methodName = signature.getMethod().getName(); 
Class<?>[] parameterTypes = signature.getMethod().getParameterTypes(); 
Annotation[][] annotations = joinPoint.getTarget().getClass().getMethod(methodName,parameterTypes).getParameterAnnotations(); 

,我不得不去通過目標類的原因是因爲被註釋的類是一個接口的實現正是如此signature.getMethod().getParameterAnnotations()返回null。

+2

謝謝你這麼多的情況下。在找到這個答案之前,我浪費了很多時間。 –

+0

對我而言,'signature.getMethod()。getParameterAnnotations()'返回接口的方法,而不是實現。所以如果註釋只在實現上,這個調用將會是null。 – oleh

+2

'signature.getMethod()。getAnnotation()'也可以。請記住註釋應該有'@Retention(RetentionPolicy.RUNTIME)'。 – Kaushik

2
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); 
    } 

此代碼覆蓋了方法屬於接口

+0

這對我有一個小小的修改。我需要使用getMethod而不是getDeclaredMethod,因爲我的方法是在超類中。 –