Java动态代理详解及实例
java动态代理
代理设计模式
定义:为其他对象提供一种代理以控制对这个对象的访问。
动态代理使用
java动态代理机制以巧妙的方式实现了代理模式的设计理念。
代理模式示例代码
public interface subject { public void dosomething(); } public class realsubject implements subject { public void dosomething() { system.out.println( "call dosomething()" ); } } public class proxyhandler implements invocationhandler { private object proxied; public proxyhandler( object proxied ) { this.proxied = proxied; } public object invoke( object proxy, method method, object[] args ) throws throwable { //在转调具体目标对象之前,可以执行一些功能处理 //转调具体目标对象的方法 return method.invoke( proxied, args); //在转调具体目标对象之后,可以执行一些功能处理 } }
import java.lang.reflect.invocationhandler; import java.lang.reflect.method; import java.lang.reflect.proxy; import sun.misc.proxygenerator; import java.io.*; public class dynamicproxy { public static void main( string args[] ) { realsubject real = new realsubject(); subject proxysubject = (subject)proxy.newproxyinstance(subject.class.getclassloader(), new class[]{subject.class}, new proxyhandler(real)); proxysubject.dosomething(); //write proxysubject class binary data to file createproxyclassfile(); } public static void createproxyclassfile() { string name = "proxysubject"; byte[] data = proxygenerator.generateproxyclass( name, new class[] { subject.class } ); try { fileoutputstream out = new fileoutputstream( name + ".class" ); out.write( data ); out.close(); } catch( exception e ) { e.printstacktrace(); } } }
动态代理内部实现
首先来看看类proxy的代码实现 proxy的主要静态变量
// 映射表:用于维护类装载器对象到其对应的代理类缓存 private static map loadertocache = new weakhashmap(); // 标记:用于标记一个动态代理类正在被创建中 private static object pendinggenerationmarker = new object(); // 同步表:记录已经被创建的动态代理类类型,主要被方法 isproxyclass 进行相关的判断 private static map proxyclasses = collections.synchronizedmap(new weakhashmap()); // 关联的调用处理器引用 protected invocationhandler h;
proxy的构造方法
// 由于 proxy 内部从不直接调用构造函数,所以 private 类型意味着禁止任何调用 private proxy() {} // 由于 proxy 内部从不直接调用构造函数,所以 protected 意味着只有子类可以调用 protected proxy(invocationhandler h) {this.h = h;}
proxy静态方法newproxyinstance
public static object newproxyinstance(classloader loader, class<?>[]interfaces,invocationhandler h) throws illegalargumentexception { // 检查 h 不为空,否则抛异常 if (h == null) { throw new nullpointerexception(); } // 获得与指定类装载器和一组接口相关的代理类类型对象 class cl = getproxyclass(loader, interfaces); // 通过反射获取构造函数对象并生成代理类实例 try { constructor cons = cl.getconstructor(constructorparams); return (object) cons.newinstance(new object[] { h }); } catch (nosuchmethodexception e) { throw new internalerror(e.tostring()); } catch (illegalaccessexception e) { throw new internalerror(e.tostring()); } catch (instantiationexception e) { throw new internalerror(e.tostring()); } catch (invocationtargetexception e) { throw new internalerror(e.tostring()); } }
类proxy的getproxyclass方法调用proxygenerator的 generateproxyclass方法产生proxysubject.class的二进制数据:
public static byte[] generateproxyclass(final string name, class[] interfaces)
我们可以import sun.misc.proxygenerator,调用 generateproxyclass方法产生binary data,然后写入文件,最后通过反编译工具来查看内部实现原理。 反编译后的proxysubject.java proxy静态方法newproxyinstance
import java.lang.reflect.*; public final class proxysubject extends proxy implements subject { private static method m1; private static method m0; private static method m3; private static method m2; public proxysubject(invocationhandler invocationhandler) { super(invocationhandler); } public final boolean equals(object obj) { try { return ((boolean)super.h.invoke(this, m1, new object[] { obj })).booleanvalue(); } catch(error _ex) { } catch(throwable throwable) { throw new undeclaredthrowableexception(throwable); } } public final int hashcode() { try { return ((integer)super.h.invoke(this, m0, null)).intvalue(); } catch(error _ex) { } catch(throwable throwable) { throw new undeclaredthrowableexception(throwable); } } public final void dosomething() { try { super.h.invoke(this, m3, null); return; } catch(error _ex) { } catch(throwable throwable) { throw new undeclaredthrowableexception(throwable); } } public final string tostring() { try { return (string)super.h.invoke(this, m2, null); } catch(error _ex) { } catch(throwable throwable) { throw new undeclaredthrowableexception(throwable); } } static { try { m1 = class.forname("java.lang.object").getmethod("equals", new class[] { class.forname("java.lang.object") }); m0 = class.forname("java.lang.object").getmethod("hashcode", new class[0]); m3 = class.forname("subject").getmethod("dosomething", new class[0]); m2 = class.forname("java.lang.object").getmethod("tostring", new class[0]); } catch(nosuchmethodexception nosuchmethodexception) { throw new nosuchmethoderror(nosuchmethodexception.getmessage()); } catch(classnotfoundexception classnotfoundexception) { throw new noclassdeffounderror(classnotfoundexception.getmessage()); } } }
proxygenerator内部是如何生成class二进制数据,可以参考源代码。
private byte[] generateclassfile() { /* * record that proxy methods are needed for the hashcode, equals, * and tostring methods of java.lang.object. this is done before * the methods from the proxy interfaces so that the methods from * java.lang.object take precedence over duplicate methods in the * proxy interfaces. */ addproxymethod(hashcodemethod, object.class); addproxymethod(equalsmethod, object.class); addproxymethod(tostringmethod, object.class); /* * now record all of the methods from the proxy interfaces, giving * earlier interfaces precedence over later ones with duplicate * methods. */ for (int i = 0; i < interfaces.length; i++) { method[] methods = interfaces[i].getmethods(); for (int j = 0; j < methods.length; j++) { addproxymethod(methods[j], interfaces[i]); } } /* * for each set of proxy methods with the same signature, * verify that the methods' return types are compatible. */ for (list<proxymethod> sigmethods : proxymethods.values()) { checkreturntypes(sigmethods); } /* ============================================================ * step 2: assemble fieldinfo and methodinfo structs for all of * fields and methods in the class we are generating. */ try { methods.add(generateconstructor()); for (list<proxymethod> sigmethods : proxymethods.values()) { for (proxymethod pm : sigmethods) { // add static field for method's method object fields.add(new fieldinfo(pm.methodfieldname, "ljava/lang/reflect/method;", acc_private | acc_static)); // generate code for proxy method and add it methods.add(pm.generatemethod()); } } methods.add(generatestaticinitializer()); } catch (ioexception e) { throw new internalerror("unexpected i/o exception"); } /* ============================================================ * step 3: write the final class file. */ /* * make sure that constant pool indexes are reserved for the * following items before starting to write the final class file. */ cp.getclass(dottoslash(classname)); cp.getclass(superclassname); for (int i = 0; i < interfaces.length; i++) { cp.getclass(dottoslash(interfaces[i].getname())); } /* * disallow new constant pool additions beyond this point, since * we are about to write the final constant pool table. */ cp.setreadonly(); bytearrayoutputstream bout = new bytearrayoutputstream(); dataoutputstream dout = new dataoutputstream(bout); try { /* * write all the items of the "classfile" structure. * see jvms section 4.1. */ // u4 magic; dout.writeint(0xcafebabe); // u2 minor_version; dout.writeshort(classfile_minor_version); // u2 major_version; dout.writeshort(classfile_major_version); cp.write(dout); // (write constant pool) // u2 access_flags; dout.writeshort(acc_public | acc_final | acc_super); // u2 this_class; dout.writeshort(cp.getclass(dottoslash(classname))); // u2 super_class; dout.writeshort(cp.getclass(superclassname)); // u2 interfaces_count; dout.writeshort(interfaces.length); // u2 interfaces[interfaces_count]; for (int i = 0; i < interfaces.length; i++) { dout.writeshort(cp.getclass( dottoslash(interfaces[i].getname()))); } // u2 fields_count; dout.writeshort(fields.size()); // field_info fields[fields_count]; for (fieldinfo f : fields) { f.write(dout); } // u2 methods_count; dout.writeshort(methods.size()); // method_info methods[methods_count]; for (methodinfo m : methods) { m.write(dout); } // u2 attributes_count; dout.writeshort(0); // (no classfile attributes for proxy classes) } catch (ioexception e) { throw new internalerror("unexpected i/o exception"); } return bout.tobytearray();
总结
一个典型的动态代理创建对象过程可分为以下四个步骤:
1、通过实现invocationhandler接口创建自己的调用处理器 ivocationhandler handler = new invocationhandlerimpl(...);
2、通过为proxy类指定classloader对象和一组interface创建动态代理类
class clazz = proxy.getproxyclass(classloader,new class[]{...});
3、通过反射机制获取动态代理类的构造函数,其参数类型是调用处理器接口类型
constructor constructor = clazz.getconstructor(new class[]{invocationhandler.class});
4、通过构造函数创建代理类实例,此时需将调用处理器对象作为参数被传入
interface proxy = (interface)constructor.newinstance(new object[] (handler));
为了简化对象创建过程,proxy类中的newinstance方法封装了2~4,只需两步即可完成代理对象的创建。
生成的proxysubject继承proxy类实现subject接口,实现的subject的方法实际调用处理器的invoke方法,而invoke方法利用反射调用的是被代理对象的的方法(object result=method.invoke(proxied,args))
美中不足
诚然,proxy已经设计得非常优美,但是还是有一点点小小的遗憾之处,那就是它始终无法摆脱仅支持interface代理的桎梏,因为它的设计注定了这个遗憾。回想一下那些动态生成的代理类的继承关系图,它们已经注定有一个共同的父类叫proxy。java的继承机制注定了这些动态代理类们无法实现对class的动态代理,原因是多继承在java中本质上就行不通。有很多条理由,人们可以否定对 class代理的必要性,但是同样有一些理由,相信支持class动态代理会更美好。接口和类的划分,本就不是很明显,只是到了java中才变得如此的细化。如果只从方法的声明及是否被定义来考量,有一种两者的混合体,它的名字叫抽象类。实现对抽象类的动态代理,相信也有其内在的价值。此外,还有一些历史遗留的类,它们将因为没有实现任何接口而从此与动态代理永世无缘。如此种种,不得不说是一个小小的遗憾。但是,不完美并不等于不伟大,伟大是一种本质,java动态代理就是佐例。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
上一篇: PhotoScan处理无人机航拍照片GCP校正流程
下一篇: php实现产品加入购物车功能(1)