利用jdk动态代理实现aop

1.需要被代理的类必须实现至少一个接口,如果使用cglib或者asm则不需要实现接口。
//接口
package com.aop;

public interface Calculator {
   public double add();
   public double mul();
}
//实现类
package com.aop;

public class XCalculator implements Calculator {
    private int a = 90;
    private int b = 38;
 @Override
 public double add() {
  return a+b;
 }

 @Override
 public double mul() {
  // TODO Auto-generated method stub
  return a-b;
 }

}
2.实现代理逻辑的类必须实现invocationHandler接口,并且在使用反射调用方法前要添加自己的代码

package com.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

 

public class CalculatorLoggingHandler implements InvocationHandler {
 
 public CalculatorLoggingHandler(Object target) {
  super();
  this.target = target;
 }


 private Log log = new Log();
 private Object target;
 
 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  log.info("the method" + method.getName() + "() begins with" + Arrays.toString(args));
  Object result = method.invoke(target, args);
  log.info("the method" + method.getName() + "() ends with " + result);
  return result;
 }
 
 public static Object creatInstance(Class c, InvocationHandler in) {
  return Proxy.newProxyInstance(c.getClassLoader(), c.getInterfaces(), in);
 }

}
//主函数

package com.aop;

import java.lang.reflect.Proxy;


public class Main {
    public static void main(String[] args) {
     Calculator xc = new XCalculator();
     Calculator cal =(Calculator) CalculatorLoggingHandler.creatInstance(xc.getClass(), new CalculatorLoggingHandler(xc));
//        System.out.println(xc.getClass().getClassLoader());
//        System.out.println(xc.getClass().getInterfaces());
     cal.add();
        cal.mul();
    }
}

运行结果

the methodadd() begins withnull
the methodadd() ends with 128.0
the methodmul() begins withnull
the methodmul() ends with 52.0

总结:

使用jdk事项动态代理比较简单,内部机制需要学习

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值