Java accessing 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){
...
开发者_如何学C 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.
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");
}
}
You can also use:
Object[] parameterList = thisJoinPoint.getArgs();
System.out.println(Arrays.toString(parameterList));
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");
}
}
精彩评论