2011-07-07 14 views
13

@LookAtThisMethod@LookAtThisParameterの2つの注釈があります。メソッドのポイントカットを@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の周りに私の解決策をモデル化しました。注釈を付けたクラスがインタフェースを実装したとthusly signature.getMethod().getParameterAnnotations()はnullを返しので、私は、ターゲットクラスを通過しなければならなかった

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

理由でした。

+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

これは私のためにわずかに修正されています。私のメソッドはスーパークラスにあったので、getDeclaredMethodの代わりにgetMethodを使う必要がありました。 –

関連する問題