簡體   English   中英

AspectJ:如何選擇給定類的子類的非注釋方法的執行?

[英]AspectJ: How to pick the execution of non-annotated methods of subclasses of a given class?

我想攔截給定類的任何子類的非注釋方法的執行。

比如說我有班級Base

public class Base {
   public void baseMethod() { //shouldn't be intercepted
      // do whatever...
   }
}

而且,最終,有人擴展了Base 無論新類名是什么,都不應截取帶有注釋@LeaveItAlone方法。 子類的所有其他方法都應該。

public class Sub extends Base {
   public void interceptedMethod1() {
      // ...
   }

   public void interceptedMethod2() {
      // ...
   }

   @LeaveItAlone
   public void NOTinterceptedMethod1() {
      // ...
   }

   @LeaveItAlone
   public void NOTinterceptedMethod2() {
      // ...
   }

我想象的是:

pointcut sub_nonannotated() : !execution(@LeaveItAlone * Base+.*(..));

但我確定上面的錯誤。

附帶問題:我如何具體攔截子類的構造函數?

實際上我只是嘗試過它,你顯然幾乎是正確的。 這對我有用:

package com.snaphop.ats.util;

public aspect Blah {
    pointcut sub_nonannotated() : !execution(@LeaveItAlone * Base+.*(..));

    pointcut sub() : execution(* Base+.*(..));

    pointcut notBase() : ! execution(* Base.*(..));

    pointcut cons() : execution(public Base+.new(..)) && ! execution(public Base.new(..));


    //advice sub class methods but not annotation or parent
    Object around() : sub_nonannotated() && sub() && notBase() {
        return proceed();
    }

    //Advice subclass constructors but not Base's constructor
    Object around() : cons() {
        return proceed();
    }
}

Adam Gent的解決方案過於復雜。 這個切入點更簡單,更清晰:

execution(!@LeaveItAlone * Base+.*(..))

或者,也許你更喜歡它(品味):

execution(* Base+.*(..)) && !@annotation(LeaveItAlone)

PS:這只涉及方法,而不是構造函數,這是你在第一句話中要求的。 我還包括Base本身的方法,而不僅僅是子類,這可能是有意義的。 如果你想要一個更復雜的東西,你仍然可以將我的解決方案與Adam的元素結合起來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM