Waiter接口
package com.mango.demo2; public interface Waiter { public void serve(); }
接口的实现类,ManWaiter
package com.mango.demo2; public class ManWaiter implements Waiter { public void serve() { System.out.println("服务中..."); } }
Demo:
package com.mango.demo2; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.junit.Test; import com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader; public class Demo2 { @Test public void fun1(){ ManWaiter manWaiter = new ManWaiter(); ClassLoader loader = this.getClass().getClassLoader(); Class[] interfaces = {Waiter.class}; InvocationHandler h = new WaiterInvocationHandler(manWaiter);//参数manWaiter表示目标对象 //得到代理对象,代理对象就是在目标对象的基础上进行了增强的对象 Waiter waiterProxy = (Waiter) Proxy.newProxyInstance(loader, interfaces, h); waiterProxy.serve(); } } class WaiterInvocationHandler implements InvocationHandler{ private Waiter waiter;//目标对象 public WaiterInvocationHandler(Waiter waiter){ this.waiter = waiter; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("你好");//增强 this.waiter.serve(); System.out.println("再见");//增强 return null; } }