简体   繁体   English

面向方面的编程Java-获取注释参数

[英]Aspect oriented programming Java - Get annotation parameters

So I have defined 3 classes, as given below. 所以我定义了3个类,如下所示。 What I am trying to do, is give input to an annotation, and then when an annotated function throws an exception, to use those parameters to do some stuff. 我想要做的是给注释提供输入,然后当注释函数抛出异常时,使用这些参数来做一些事情。

So basically, in the CreateFluxoTicket class in the aferThrowing function, I want to gain access to the "shortDescription" and "details" attributes. 所以基本上,在aferThrowing函数的CreateFluxoTicket类中,我希望获得对“shortDescription”和“details”属性的访问权限。

I went through numerous links and answers, but I fail to get the parameters. 我经历了很多链接和答案,但我没有得到参数。 One thing which I tried to do is shown below, but the parameter list is empty (The output is - "Parameter Types size = 0") 我尝试做的一件事如下所示,但是参数列表为空(输出为-“ Parameter Types size = 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);
            }
        }
    }
}

You can bind the annotation to a parameter similar to the exception. 您可以将注释绑定到类似于异常的参数。 Try this: 尝试这个:

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

As you can see, I also limited the pointcut to method execution s because otherwise call s would also trigger the advice and you would see the output twice. 如您所见,我还将切入点限制为方法execution s,因为否则call s也会触发建议,并且您将看到两次输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM