Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java accessing function call parameters via AspectJ

Tags:

java

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 right after ClassX.fX(1,"testY") method call and will give me access to ClassY.fY(String arg1, String arg2, int arg3) function call arguments (i.e arg1, arg2 and arg3) at the same time,

I tried this one but it didnt 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 would be the pointcut and advice changes to take those values in the correct place?

Thanks in advance.

like image 377
huseyinarslan Avatar asked Feb 11 '11 07:02

huseyinarslan


2 Answers

You will have to use a wormhole pattern to capture the parameters and make them available at a later joinpoint.

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

Here is a small program I wrote that solves the problem you are describing:

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");
    }
}
like image 110
Andrew Eisenberg Avatar answered Nov 08 '22 12:11

Andrew Eisenberg


You can also use:

Object[] parameterList = thisJoinPoint.getArgs();

System.out.println(Arrays.toString(parameterList));
like image 39
Brady Avatar answered Nov 08 '22 14:11

Brady