[ACCEPTED]-Getting a return value or exception from AspectJ?-pointcut

Accepted answer
Score: 15

You can use after() returning and after() throwing advices as in beginning 3 of the following document. If you're using @AspectJ syntax please 2 refer to @AfterReturning and @AfterThrowing annotations (you can find 1 samples here).

Score: 9

You can also get return value using after returing advice.

package com.eos.poc.test;   

public class AOPDemo {
            public static void main(String[] args) {
                AOPDemo demo = new AOPDemo();
                String result= demo.append("Eclipse", " aspectJ");
           }
            public String append(String s1, String s2) {
                System.out.println("Executing append method..");
                return s1 + s2;
          }

}

The 1 defined aspect for getting return value:

public aspect DemoAspect {
    pointcut callDemoAspectPointCut():
        call(* com.eos.poc.test.AOPDemo.append(*,*));

    after() returning(Object r) :callDemoAspectPointCut(){
        System.out.println("Return value: "+r.toString()); // getting return value

    }
Score: 7

Using an around() advice, you can get the return 6 value of the intercepted method call by 5 using proceed(). You can even change the value returned 4 by the method if you want to.

For instance, suppose 3 you have a method m() inside class MyClass:

public class MyClass {
  int m() {
    return 2;
  }
}

Suppose 2 you have the following aspect in its own 1 .aj file:

public aspect mAspect {
   pointcut mexec() : execution(* m(..));

   int around() : mexec() {    
     // use proceed() to do the computation of the original method
     int original_return_value = proceed();

     // change the return value of m()
     return original_return_value * 100;
   }
}

More Related questions