4

我想知道是否有办法从主函数中获取变量并在方面使用它。我知道建议会在之前和之后执行,before()但他们怎么能得到和/或?after()methodeOneVAR1VAR2

public class AOPdemo {

    public static void main(String[] args) {
        AOPdemo aop = new AOPdemo();
        aop.methodeOne(5);//Call of the function wrapped in the aspect
        int VAR1;
        //VAR1 variable im trying to send to the aspect
    }
    public void methodeOne(int VAR2){
        //VAR2 another variable i'm trying to send to the aspect
        System.out.println("method one");
    }
}
public aspect myAspect {
    pointcut function():
    call(void AOPdemo.methode*(..));

    after(): function(){
        int VAR1;//Trying to get this variables
        int VAR2;
        System.out.println("aspect after...");  
    }

    before(): function(){
        System.out.println("...aspect before");
    }
}
4

2 回答 2

3

您不能将任意变量传递给拦截器。但是拦截器可以访问传递给被拦截方法的参数,以及调用该方法的对象。你可以这样做:

public aspect myAspect {
    pointcut function(AOPdemo t, int var2):
    execute(void AOPdemo.methode*(..)) && target(t) && args(var2);

    after(AOPdemo t, int var2): function(t, var2){
        // var2 is directly available,
        // var1 could be accessible through t provided there is a getter :
        int var1 = t.getVar1();
        System.out.println("aspect after...");  
    }
    ...
}
于 2015-07-15T09:55:16.570 回答
1

方面用于拦截方法,它们只会看到发送到该特定方法的变量,所以我看不到任何方法可以从方法外向它们发送数据。

除非你把VAR1它放在其他地方(例如在一个静态变量中)并将它放在拦截器中,这根本不是一个好习惯!

于 2015-07-15T08:36:19.223 回答