2011-07-07 19 views
13

@LookAtThisMethod ve @LookAtThisParameter iki ek açıklama var, @LookAtThisMethod ile ilgili yöntemlerin etrafında bir nokta kesme varsa, @LookAtThisParameter ile açıklamalı olan söz konusu yöntemin parametrelerini nasıl ayırım? ÖrneğinBir nokta işaretinin içinde ek açıklamalı parametreler alın

:

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

} 

cevap

29

ben farklı ama benzer soruya bu other answer etrafında çözüm modellenmiştir. açıklamalı edildi sınıf bir arayüzün bir uygulama oldu ve böylelikle, signature.getMethod().getParameterAnnotations() boş döndü çünkü

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

Ben hedef sınıfına geçmesi gerekiyordu nedeni

oldu.

+2

Çok teşekkür ederim arayüzüne ait senaryoyu kapsar. Bu cevabı bulmadan çok zaman harcadım. –

+0

Benim için 'signature.getMethod(). GetParameterAnnotations() ', arabirimin yöntemini döndürür ve uygulamayı değil. Yani ek açıklama sadece uygulamada ise, bu çağrı ile null olacaktır. – oleh

+2

'signature.getMethod(). GetAnnotation()' da çalışır. Sadece hatırlatmayı hatırla: '@Retention (RetentionPolicy.RUNTIME) 'olmalıdır. – 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); 
    } 

Bu kod Yöntem

+0

Bu benim için ufak bir değişiklik yapıldı. Yöntemim bir üst sınıfta olduğu için getDeclaredMethod yerine getMethod kullanmam gerekiyordu. –

İlgili konular