微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从AspectJ获取返回值或异常?

如何解决从AspectJ获取返回值或异常?

| 我可以从建议的方法调用获取签名和参数,但是我无法弄清楚如何获取返回值或异常。我有点假设可以使用around和procedure以某种方式完成它。     

解决方法

您可以像下面的文档开头那样使用
after() returning
after() throwing
建议。如果您使用@AspectJ语法,请参考
@AfterReturning
@AfterThrowing
注释(您可以在此处找到示例)。     ,重提建议后,您还可以使用返回值。
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;
          }

}
获取返回值的已定义方面:
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

    }
    ,使用
around()
建议,可以使用
proceed()
获得截获的方法调用的返回值。您甚至可以根据需要更改方法返回的值。 例如,假设您在类
MyClass
中有一个方法
m()
public class MyClass {
  int m() {
    return 2;
  }
}
假设您自己的.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;
   }
}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。