//代理工厂 public class ProxyFactory { private Object targetObj; public ProxyFactory(Object targetObj) { this .targetObj = targetObj; } /** * jdk动态代理 一定需要代理对象实现接口 * 区别于cglib的动态代理,cglib需要导入相关jar包,不需要实现接口 * @return */ public Object getProxy() { ClassLoader loader = targetObj.getClass().getClassLoader(); Class<?>[] interfaces = targetObj.getClass().getInterfaces(); InvocationHandler inv = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println( "执行方法" ); return method.invoke(targetObj, args); } }; return Proxy.newProxyInstance(loader, interfaces, inv); } } //代理客户端 public class ProxyClinet { public static void main(String[] args) { OrderDao orderDao = new OrderDaoImpl(); ProxyFactory factor = new ProxyFactory(orderDao); OrderDao proxy = (OrderDao) factor.getProxy(); System.out.println(proxy); } } //被代理实体类 public class OrderDaoImpl implements OrderDao { @Override public void createOrder() { System.out.println( "创建还款订单" ); } } //被代理接口 public interface OrderDao { public void createOrder(); } |