动态代理类(以下简称为代理类)是一个实现在创建类时在运行时指定的接口列表的类,该类具有下面描述的行为。 代理接口 是代理类实现的一个接口。代理实例 是代理类的一个实例。 每个代理实例都有一个关联的调用处理程序 对象,它可以实现接口 InvocationHandler。通过其中一个代理接口的代理实例上的方法调用将被指派到实例的调用处理程序的 Invoke 方法,并传递代理实例、识别调用方法的 java.lang.reflect.Method 对象以及包含参数的 Object 类型的数组。调用处理程序以适当的方式处理编码的方法调用,并且它返回的结果将作为代理实例上方法调用的结果返回。
1,被代理类 的接口 Proxied
Java代码 // 被代理类 需实现的 接口 public interface Proxied { void doSomething(); void doSomethingElse(String str); }
2,一个 Proxied接口 的实现类(被代理类)
Java代码 public class ConcreteProxied implements Proxied { @Override public void doSomething() { try { Thread.sleep(100); } catch (InterruptedException e) { System.err.println("Error : InterruptedException"); } System.out.println(this.getClass().getSimpleName() + " >> doSomething ."); } @Override public void doSomethingElse(String str) { try { Thread.sleep(150); } catch (InterruptedException e) { System.err.println("Error : InterruptedException"); } System.out.println(this.getClass().getSimpleName() + " >> doSomethingElse , argument = " + str + "."); } }
3,TimingInvocationHandler 类,实现了 InvocationHandler 接口
Java代码 import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class TimeingInvocationHandler implements InvocationHandler{ //被代理的对象 private Object proxied; public TimeingInvocationHandler(Object proxied){ this.proxied = proxied; } // 参数 proxy 表示代理类的对象 // 参数 method 表示被代理类 和 代理类 都实现的接口 的方法对象 // 参数 args 表示方法 method 的参数数组 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(method.getDeclaringClass().getName()); long currentTimeMillis = System.currentTimeMillis(); Object ret = method.invoke(proxied, args); System.out.println(this.getClass().getSimpleName()+" >> wastes time : " +(System.currentTimeMillis() - currentTimeMillis)+"ms"); return ret; } }
4,测试类 Test
Java代码 import java.lang.reflect.Proxy; public class TestProxy { public static void main(String[] args) { Proxied proxied = new ConcreteProxied(); proxied.doSomething(); proxied.doSomethingElse("only a String"); // 生成一个代理实例,这个代理实现了 Proxied 接口 // 对这个代理(proxy)的方法的调用 会 重定向到 TimeingInvocationHandler 的 invoke 方法 Proxied proxy = (Proxied) Proxy.newProxyInstance(Proxied.class .getClassLoader(), // 类加载器 new Class[] { Proxied.class }, // 代理要实现的接口 new TimeingInvocationHandler(proxied) // 调用处理器 ); proxy.doSomething(); proxy.doSomethingElse("only a String"); } }