2015-02-11 48 views
0

所以我定義了3個類,如下所示。我想要做的是給輸入註釋,然後當註釋函數拋出異常時,使用這些參數來做一些事情。面向方面的編程Java - 獲取註釋參數

因此,基本上,在aferThrowing函數的CreateFluxoTicket類中,我想獲得對「shortDescription」和「details」屬性的訪問權限。

我經歷了無數的鏈接和答案,但我沒有得到參數。我試圖做的一件事是如下圖所示,但參數列表爲空(輸出爲 - 「參數類型的大小= 0」)

public class TemporaryClass { 
    @Fluxo(shortDescription = "shortDescription", details = "details") 
    public void tempFluxo() { 
     System.out.println(50/0); 
    } 
} 

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface Fluxo { 
    String shortDescription(); 
    String details(); 
} 

@Aspect 
public class CreateFluxoTicket { 
    @AfterThrowing(pointcut = "@annotation(metrics.annotations.Fluxo)", throwing = "e") 
    public void afterThrowingException(JoinPoint jointPoint, Throwable e) { 
     Signature signature = jointPoint.getStaticPart().getSignature(); 
     if (signature instanceof MethodSignature) { 
      MethodSignature ms = (MethodSignature) signature; 
      Class<?>[] parameterTypes = ms.getParameterTypes(); 
      System.out.println("Parameter Types size = " + parameterTypes.length); 
      for (final Class<?> pt : parameterTypes) { 
       System.out.println("Parameter type:" + pt); 
      } 
     } 
    } 
} 

回答

0

您可以註釋綁定到類似異常的參數。試試這個:

package metrics.aspect; 

import metrics.annotations.Fluxo; 

import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.annotation.AfterThrowing; 
import org.aspectj.lang.annotation.Aspect; 

@Aspect 
public class CreateFluxoTicket { 
    @AfterThrowing(
     pointcut = "execution(* *(..)) && @annotation(fluxo)", 
     throwing = "throwable" 
    ) 
    public void afterThrowingException(
     JoinPoint thisJoinPoint, 
     Fluxo fluxo, 
     Throwable throwable 
    ) { 
     System.out.println(thisJoinPoint + " -> " + fluxo.shortDescription()); 
    } 
} 

正如你所看到的,我也限制了切入點方法execution是因爲否則call S還可能引發的建議,你會看到輸出的兩倍。