Proxy.newProxyInstance()

来源:互联网 发布:for 迭代器 python 编辑:程序博客网 时间:2024/04/25 23:06
<strong><span style="font-size:14px;">import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;class DynamicProxyHandler implements  InvocationHandler{private Object proxied;public DynamicProxyHandler(Object proxied) {this.proxied = proxied;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {System.out.println("**** proxy: " + proxy.getClass() + ", method: " + method + ", args: " + args);if(args != null)for(Object arg : args)System.out.println(" " + arg);return method.invoke(proxied, args);}}public class SimpleDynamicProxy {public static void consumer(Interface iface) {iface.doSomething();iface.somethingElse("bonobo");}public static void main(String[] args){RealObject real = new RealObject();consumer(real);Interface proxy = (Interface) Proxy.newProxyInstance(Interface.class.getClassLoader(), new Class[] {Interface.class}, new DynamicProxyHandler(real));consumer(proxy);}}</span></strong>
<strong><span style="font-size:14px;"></span></strong>
<strong><span style="font-size:14px;">Proxy.newProxyInstance() 可以创建动态代理,这发方法需要得到  一个类加载器(通常可以从已经被加载的对象中获取其类加载器) 一个希望该代理实现的接口列表(不是类或者抽象类) 以及InvocationHandler 接口的实现</span></strong>
<strong><span style="font-size:14px;"><span style="white-space:pre"></span>invoke()方法中传递进来了代理对象,在invoke()内部,在代理上调用方法时需要格外小心,应为对接口的调用将被重定向为代理的调用</span></strong>

0 0
原创粉丝点击