这几天温习了一下关于java反射的内容,发现JAVA提供了动态代理的默认实现(以前没用到过),主要由Proxy类,InvocationHandler接口(在java.lang.reflect包中)组成。
下面演示一个使用 Proxy 和 InvocationHandler 类实现动态代理的例子,这个动态代理对被代理对象的方法执行时间进行计时,并将执行时间打印输出到控制台。
1、被代理类的接口Proxied
Java代码
package Test1; public interface Proxied { |
2、一个 Proxied接口 的实现类(被代理类)
Java代码
package Test1; 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代码
package Test1; 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; } } |