4

I was wondering if there is a way to get a variable from the main function and use it in the aspect. I know before() and after() advices will execute before and after methodeOne but how can they get VAR1 and/or 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");
    }
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
Valkie
  • 41
  • 4

2 Answers2

3

You cannot pass an arbitrary variable to an interceptor. But the interceptor can get access to the parameters passed to the intercepted method, and to the object on which the method was called. You could do :

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...");  
    }
    ...
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

Aspects are for intercepting methods, and they will only see variables send to that particular method, so i don`t see any way to send them data from out of the method.

Unless u put VAR1 somewhere else ( for example in an static variable) and get it in the interceptor which is not a good practice at all!!

alizelzele
  • 892
  • 2
  • 19
  • 34