2014-12-04 85 views
0

我有方法A和方法B.我只希望在方法A中調用方法B時將切入點附加到方法A. Aspets有可能嗎?謝謝。 例子: 方面代碼:帶有特定方法調用方法的切入點

package aspects.unregistrator; 

import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.annotation.After; 

import com.core.Item; 

public aspect Unregistrator { 

pointcut unRegistrated() : within(tasks..*) && call(* find(..)); 

    after() : unRegistrated() { 
     Item.unregisterAll(); 
    } 
} 

這將在每一個方法find()方法的每次調用後連接點的任務包

,但我需要unregisterAll(),它包含找到每個方法後執行()調用,就像這樣:

package tasks.helpers; 

public class TableHelper { 

public static void clickButtonInCell(final WTable table) { 
    table.find(SubitemFactory(Element.BUTTON)).click(); 
    Item.unregisterAll(); 
} 
+0

我這麼認爲,但這是StackOverflow。所以請張貼代碼,不要問這樣一般的,不精確的問題。然後你可以描述你想要在代碼中實現什麼。 – kriegaex 2014-12-05 10:31:56

回答

1

我剛找到一個方法,使這可能使用AspectJ語言的兩個特殊的關鍵字:thisEnclosingJoinPointStaticPartthisJoinPointStaticPart。這樣,您需要保留調用find()方法的封閉連接點(在您的案例中爲public static void clickButtonInCell(final WTable table))。然後,您需要檢查每個方法執行find()方法的封閉連接點是否與其連接點相同。

例如:

class TableHelper { 

    public static void clickButtonInCell(final WTable table) { 
     System.out.println("clickButtonInCell"); 
     table.find(); 
     // Item.unregisterAll() will be called after find() 
    } 

    public static void clickButtonInX(final WTable table) { 
     System.out.println("clickButtonInX"); 
     table.doSomething(); 
     // even if Item.unregisterAll() is matched with this method execution, it will not work 
    } 

} 


public aspect Unregistrator { 

    String enclosedJP = ""; 

    pointcut unRegistrated() : within(tasks..*) && call(* find(..)); 

    after() : unRegistrated() { 
     enclosedJP = thisEnclosingJoinPointStaticPart.toLongString(); 
    } 

    pointcut doPointcut(): within(tasks..*) && execution(* *(..)); 

    after() : doPointcut(){ 
     if(enclosedJP.equals(thisJoinPointStaticPart.toLongString())) 
      Item.unregisterAll(); 
    } 
} 

我希望這可以幫助你需要什麼。

+1

非常感謝。它有助於! – Pavel 2014-12-12 11:24:17