基本介绍

静态代理


动态代理

public interface ITeacherDao { void teach();}
public class TeacherDao implements ITeacherDao { @Override public void teach() { System.out.println("teach"); }}
public class ProxyFactory { private Object target; public ProxyFactory(Object target) { this.target = target; } public Object getProxyInstance() { return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), (proxy, method, args) -> { System.out.println("JDK代理开始"); Object returnVal = method.invoke(target, args); return returnVal; }); }}
public class Client { public static void main(String[] args) { //创建目标对象 ITeacherDao target = new TeacherDao(); //给目标对象创建代理对象 ProxyFactory proxyFactory = new ProxyFactory(target); ITeacherDao proxyInstance = (ITeacherDao) proxyFactory.getProxyInstance(); proxyInstance.teach(); }}