//动态代理 public class ProxyTest2 { public static void main(String[] args) { SuperMan superMan = new SuperMan(); Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan); System.out.println(proxyInstance.dream()); proxyInstance.est("菠萝"); } } //接口 interface Human{ String dream(); void est(String food); } //被代理类 class SuperMan implements Human{ @Override public String dream() { return "my dream is fly"; } @Override public void est(String food) { System.out.println("I like to eat "+food); } } //代理类工厂 class ProxyFactory { public static Object getProxyInstance(Object object) { //obj : 被代理类的对象 //通过Proxy 创建一个代理类 /* 三个参数: loader :被代理类的加载器 interface : 代理类实现的接口 invocationHandler : 动态的调用被代理类的方法 */ MyInvocationHandler myInvocationHandler = new MyInvocationHandler(); myInvocationHandler.bind(object); return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),myInvocationHandler); } } //invocationHandler的实现类 class MyInvocationHandler implements InvocationHandler{ private Object object; //需要使用被代理类的对象赋值 public void bind(Object object){ this.object=object; } //当通过代理类调用方法时 , 就会通过invoke()方法调用被代理类的方法 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(object,args); } }