我想知道是否有办法从主函数中获取变量并在方面中使用它。我知道 before()
和 after()
建议将在 methodeOne
之前和之后执行,但它们如何获得 VAR1
和/或 VAR2
?
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");
}
}
最佳答案
您不能将任意变量传递给拦截器。但是拦截器可以访问传递给被拦截方法的参数,以及调用该方法的对象。你可以这样做:
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...");
}
...
}
关于java - 如何在 Java 中将变量发送到 Aspect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31423508/