参考如下
反射:https://www.cnblogs.com/fzz9/p/7738381.html
代理:https://www.cnblogs.com/cenyu/p/6289209.html
反射
反射案例
代理
静态代理
第一步:创建普通类接口Dao
public interface Dao { public void save(); }
第二步:创建普通类,实现Dao接口
public class DaoImpl implements Dao{ @Override public void save() { System.out.println("存钱"); } }
第三步:测试
class DaoProxy implements Dao { private Dao target; public DaoProxy(Dao target) { super(); this.target = target; } @Override public void save() { System.out.println("开始"); target.save(); System.out.println("结束"); } } Dao target = new DaoImpl(); DaoProxy daoProxy = new DaoProxy(target); daoProxy.save();
动态代理
第一步和第二步如上
第三步:测试
DaoImpl dao = new DaoImpl(); Dao daoProxy = (Dao)Proxy.newProxyInstance(dao.getClass().getClassLoader(), dao.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("开始前"); Object invoke = method.invoke(dao, args); System.out.println("开始后"); return invoke; } }); daoProxy.save();
Cglib代理
第一步和第二步如上
第三步:新建一个实现代理的类
需要导入spring核心包
需要新建一个
class CglibProxy implements MethodInterceptor{ private Object target; public CglibProxy(Object target) { super(); this.target = target; } //获得代理对象 public Object get() { Enhancer en = new Enhancer(); en.setSuperclass(target.getClass()); en.setCallback(this); return en.create(); } @Override public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable { System.out.println("开始"); Object invoke = arg1.invoke(target, arg2); System.out.println("结束"); return invoke; } }
第四步:测试
Dao dao = new DaoImpl(); CglibProxy c = new CglibProxy(dao); Dao daoProxy = (Dao)c.get(); daoProxy.save();