2015-02-11 46 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还可能引发的建议,你会看到输出的两倍。