在 AspectJ 中,获取自定义注解的参数

2023-02-27  本文已影响0人  littlefogcat

举个例子,我们有一个注解:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DebugLog {
    boolean printParams() default true;
}

// 使用注解
@DebugLog(printParams = false)
public void onCreate(Bundle savedInstanceState) {}

这时候,如何获取 printParams 参数的值呢?
如下:

    // 切面类中
    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        // ……
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        DebugLog annotation = method.getAnnotation(DebugLog.class);
        boolean printParams = annotation.printParams();
        // ……
    }

即,将 joinPoint.getSignature() 强制转换成 MethodSignature 类型,就可以获取到对应的 Method 对象了,然后就能获取到注解参数了。

上一篇 下一篇

猜你喜欢

热点阅读