美文网首页
在 AspectJ 中,获取自定义注解的参数

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

作者: littlefogcat | 来源:发表于2023-02-27 11:18 被阅读0次

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

@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 对象了,然后就能获取到注解参数了。

相关文章

网友评论

      本文标题:在 AspectJ 中,获取自定义注解的参数

      本文链接:https://www.haomeiwen.com/subject/oguhldtx.html