【问题标题】:@AspectJ pointcut for subclasses of a class with an annotation带有注解的类的子类的@AspectJ 切入点
【发布时间】:2014-03-19 20:35:41
【问题描述】:

我正在寻找一个切入点,该切入点与类中的方法执行相匹配,该类是具有特定注释的类的子类。优秀的AspectJ cheat sheet 帮助我创建了以下切入点:

within(@my.own.annotations.AnnotationToMatch *) && execution(* *(..))

这匹配带有@AnnotationToMatch 的类A 的所有方法调用,但不匹配扩展A 的类B 的方法。如何同时匹配两者?

【问题讨论】:

    标签: java aop aspectj


    【解决方案1】:
    public aspect AnnotatedParentPointcutAspect {   
    
    //introducing empty marker interface
    declare parents : (@MyAnnotation *) implements TrackedParentMarker;
    
    public pointcut p1() : execution(* TrackedParentMarker+.*(..));
    
    before(): p1(){
        System.out.println("Crosscutted method: "
                +thisJoinPointStaticPart.getSignature().getDeclaringTypeName()
                +"." 
                +thisJoinPointStaticPart.getSignature().getName());
    }
    }
    

    【讨论】:

    • 谢谢!为了他人的利益:如果您使用注释样式,则声明父母将转换为 @DeclareParents("(@MyAnnotation *)") private TrackedParentMarker emptyMixinForClassesWithMyAnnotation;
    • 这适用于超类,但不适用于接口。 IE。在诸如MyInterface o = new MyClass() 之类的代码中,它看起来像MyClass 在接口之前加载并且条件不匹配。在语句修复问题之前添加println(MyInterface.class),但对于库方面来说不是可行的要求。有什么想法吗?
    【解决方案2】:

    另一种更简单的可能性是将注释声明为@Inherited - 因此它也适用于子类。

    【讨论】:

    • 但是如果你不能将注解声明为@Inherited,它将不起作用。例如。来自第三方库的基类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2023-04-08
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2014-06-25
    相关资源
    最近更新 更多