java - 如何在 Java 中将变量发送到 Aspect?

标签 java eclipse aspectj ajdt

我想知道是否有办法从主函数中获取变量并在方面中使用它。我知道 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/

相关文章:

java - 数据库 session 上下文中的更改随着池连接的重用而持续存在

java - Play Framework : Mixing Java and Scala controller/views

java - 如何迭代map避免NPE?

eclipse - 自动安装和配置 Eclipse 插件

android - android-sdk\tools 中缺少 Emulator.exe

java - Eclipse:JVM 共享库不包含 JNI_CreateJavaVM 符号

java - Aspectj 中的 LTW 问题

java - 如何使用Java洗牌(尝试使用hashmap,不起作用)?

java - Spring 中 AspectJ AOP 配置的问题:java.lang.IllegalArgumentException: error at::0 找不到引用的切入点

java - 记录用户操作