I am new to aspectj and I had a function which gets the integer variable and adds 100 to it as follows
public static void add(int no)
{
no=no+100;
}
My aspect is as follows
pointcut printMessage(int m) : execution(* add(..)) && args(m);
after(int m) returning: printMessage(m) {
System.out.println(m);
}
I am calling the function with the value 10. But when I run the code, it returns the result as 10. can any one tell me why it is not returning 110. correct me if I am wrong
Because in java an int is not modifiable. If you write
int i = 10;
add(i);
System.out.println(i);
You will still get 10. So your aspect does what you asked : you pass a variable of value 10 to a function, the fuction does what it wants with its local copy, and on return the variable is unchanged
Edit :
If you want to get a modified value, you could pass a modifiable variable like an array, or more simply use the return value (because your current add is a no op) :
Edit 2 here is full test code :
public class AspectTest {
public static int add(int i) {
return i+100;
}
@Test
public void test() throws Exception {
int j = add(10);
assertEquals(110, j);
add(20);
}
}
and :
aspect A {
pointcut printMessage() : execution(* add(..));
after() returning (int m): printMessage() {
System.out.println(m);
}
}
Output :
Running ...AspectTest
110
120
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.214 sec