Access Java function call parameters via AspectJ

package a;
    Class X
        public fX(int i, String s);

package b;
    Class Y
        public fY(String arg1, String arg2, int arg3){
            ...
            ClassX.fX(1,"testY");
            // Need to execute some stuff right here after this call

        }

    Class Z
        public fZ(int n, int m){
            ClassX.fX(2,"testZ");
        }

I need such a pointcut and advice that it will point to immediately after calling the ClassX.fX (1, ​​"testY") method and give me access to ClassY.fY (String arg1, String arg2, int arg3) function call arguments (for example , arg1, arg2 and arg3) at the same time,

I tried this one but it did not work.

pointcut ParameterPointCut(String arg1, String arg2, int arg3) :
    withincode (public String ClassY.fY(String,String,int))&&
    call(public String ClassX.fX(int, String)) &&
    args(arg1,arg2,arg3);


after(String arg1, String arg2, int arg3): ParameterPointCut(arg1,arg2,arg3){
        System.out.println("arg1 =" + arg1);
    }

What will be the pointcut and advice changes to accept these values ​​in the right place?

Thanks in advance.

+5
source share
3 answers

You will need to use the wormhole template to capture the parameters and make them available at a later point in the connection.

http://my.safaribooksonline.com/9781933988054/the_wormhole_pattern

, , , :

public aspect Aspect {

    pointcut outerMethod(String arg1, String arg2, int arg3) : 
        execution(public void Y.fY(String,String,int)) && 
        args(arg1, arg2, arg3); 

    pointcut innerMethod() : call(public void X.fX(int, String));

    after(String arg1, String arg2, int arg3) : 
        cflow(outerMethod(arg1, arg2, arg3)) &&
        innerMethod() {
        System.out.println("I'm here!!!");
        System.out.println(arg1 + " " + arg2 + " " + arg3);
    }

    public static void main(String[] args) {
        Y.fY("a", "b", 1);
    }
}

class X {
    public static void fX(int i, String s) {

    }
}

class Y {
    public static void fY(String arg1, String arg2, int arg3) {
        X.fX(1, "testY");
    }
}
+7

:

Object[] parameterList = thisJoinPoint.getArgs();

System.out.println(Arrays.toString(parameterList));
+3
public aspect ExampleAspect {

pointcut methodCall() : execution(public void printStuff(..));

before(): methodCall(){
    System.out.println(thisJoinPoint.getArgs().toString()
            + "  <--- printed by the aspect");
}

}

class AspectTest {

public static void printStuff(String s) {
    System.out.println(s + "  <---  printed by the method");
}

public static void main(String[] args) {
    printStuff("printedParameter");
}
}
0
source

All Articles