从AspectJ获取返回值或异常?

Dal*_*las 15 aspectj return exception pointcut

我能够从建议的方法调用中获取签名和参数,但我无法弄清楚如何获取返回值或异常.我有点假设它可以以某种方式使用并继续.

Con*_*ner 14

您可以像在以下文档的开头一样使用after() returningafter() throwing建议.如果您正在使用@AspectJ语法,请参阅和注释(您可以在此处找到示例).@AfterReturning@AfterThrowing


MAD*_*N M 9

您还可以在撤回建议使用返回值.

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;
          }

}
Run Code Online (Sandbox Code Playgroud)

获取返回值的已定义方面:

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

    }
Run Code Online (Sandbox Code Playgroud)


Edu*_*rra 6

使用around()建议,您可以使用获取截获的方法调用的返回值proceed().如果需要,您甚至可以更改方法返回的值.

例如,假设您m()在类中有一个方法MyClass:

public class MyClass {
  int m() {
    return 2;
  }
}
Run Code Online (Sandbox Code Playgroud)

假设您在自己的.aj文件中有以下方面:

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;
   }
}
Run Code Online (Sandbox Code Playgroud)