动态代理模式
1 日志代理
实现方式 1 实现接口 jdk动态代理 2 继承 Cglib、Javassist 动态代理
java的动态代理 -> python的装饰器 -> golang和python函数的闭包
package com.itstaredu.spring.aop.before; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; /** * @author lubai * @version 1.0 * @date 2019/12/10 12:43 下午 * <p> * 1 proxy 所用动态代理类的父类 生产代理类 或代理对象 * <p> * 3 getProxyClass 获取代理类的Class对象 * 4 newProxyInstance 生成代理类的实例对象 * <p> * 2 invocationHandler 动态代理 具体的处理的内容编写 即 附加功能 * <p> * 代理的目标是谁 获取代理对象 代理里面扩展的功能 **/ public class ArithmeticCalculatorProxy { /** * 目标对象 */ private ArithmeticCalculator target; public ArithmeticCalculatorProxy(ArithmeticCalculator target) { this.target = target; } public Object getProxy() { /** * loader ClassLoader对象 类加载器对象 帮助我们动态生成类 */ ClassLoader loader = target.getClass().getClassLoader(); Class<?>[] interfaces = target.getClass().getInterfaces(); Object proxy = Proxy.newProxyInstance(loader, interfaces, new InvocationHandler() { /** * * @param proxy * @param method 正在被调用的方法对象 * @param args 正在被调用的方法 所用到的参数 * @return * @throws Throwable */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("the method start with" + method.getName() + Arrays.asList(args)); Object result = method.invoke(target, args); System.out.println("the method" + method.getName() + "end with" + result); return result; } }); return proxy; } }