/* * 被代理类接口 */ public interface ITest { public String dosth(); } /* * 被代理类 */ public class A implements ITest { public String dosth() { System.out.println("Real do "); return "A"; } } /* * 动态代理类 */ public class DynmicProxy implements InvocationHandler { private Object obj; public DynmicProxy(Object obj){ this.obj = obj; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println("before invoke " + method); Object res = method.invoke(obj, args); System.out.println("after invoke " + method); return res; } } /* * 调用 */ public class Client { public static void main(String[] args) { A a = new A();//to be proxyed InvocationHandler h = new DynmicProxy(a); ITest proxyclass = (ITest) Proxy.newProxyInstance(A.class.getClassLoader(), A.class.getInterfaces(), h); proxyclass.dosth(); } } 使用JAVA中的动态代理类,可以很灵活的产生动态代理对象,避免了编写很多代理类的情况。 主要使用反射包中的InvocationHandler接口 和 Proxy类 示例代码: