1. 接口 package dynamic.proxy; public interface ISubject { public void request(); } 2. 业务类(要被代理的类) package dynamic.proxy; public class RealSubject implements ISubject { @Override public void request() { System.out.println("RealSubject request() ...."); } } 3. 代理类 package dynamic.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class DynamicProxy implements InvocationHandler { // 被代理类的实例 Object obj = null; public DynamicProxy(Object obj){ this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 真正服务执行前,可动态添加的行为 Object result = method.invoke(this.obj, args); // 真正服务之星后,可动态添加的行为 return result; } } 4. 测试类 package dynamic.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; public class Client { public static void main(String[] args){ ISubject realSubject = new RealSubject(); ClassLoader loader = realSubject.getClass().getClassLoader(); Class<?>[] interfaces = realSubject.getClass().getInterfaces(); InvocationHandler handler = new DynamicProxy(realSubject); ISubject proxy = (ISubject) Proxy.newProxyInstance(loader, interfaces, handler); proxy.request(); System.out.println(proxy.getClass().getName()); } }