前言
java proxy主要用于创建动态代理实例,这些实例实现了指定的一组接口,并在调用方法时将调用转发给指定的调用处理器(invocationhandler)。这种机制常用于实现aop(面向切面编程)框架、rpc(远程过程调用)框架等,以及任何需要动态改变对象行为的场景。
一、proxy代码示例
在这个示例中,我们创建了一个实现了 myinterface 接口的匿名内部类对象 myobject。然后,我们创建了一个 myinvocationhandler 对象,并将 myobject 作为目标对象传递给它。接下来,我们使用 proxy.newproxyinstance 方法创建了一个代理对象 proxy,并将 myinterface 接口和 handler 作为参数传递给它。最后,我们调用代理对象的 dosomething 方法,这个方法调用会转发给 handler 的 invoke 方法,并在其中添加自定义逻辑。
interface myinterface { void dosomething(); } class myinvocationhandler implements invocationhandler { private object target; public myinvocationhandler(object target) { this.target = target; } @override public object invoke(object proxy, method method, object[] args) throws throwable { system.out.println("before method call"); object result = method.invoke(target, args); system.out.println("after method call"); return result; } } public class dynamicproxyexample { public static void main(string[] args) { myinterface myobject = new myinterface() { @override public void dosomething() { system.out.println("doing something"); } }; myinvocationhandler handler = new myinvocationhandler(myobject); myinterface proxy = (myinterface) proxy.newproxyinstance( myinterface.class.getclassloader(), new class<?>[]{myinterface.class}, handler ); proxy.dosomething(); // this will call the proxy's dosomething method, which forwards to the handler's invoke method. } }
二、底层源码分析
- 从newproxyinstance这个入口来看看proxy的重点方法。
public static object newproxyinstance(classloader loader, class<?>[] interfaces, invocationhandler h) throws illegalargumentexception { //将接口clone,之后对此clone类进行操作 final class<?>[] intfs = interfaces.clone(); //进行权限检查 final securitymanager sm = system.getsecuritymanager(); if (sm != null) { checkproxyaccess(reflection.getcallerclass(), loader, intfs); } /* * look up or generate the designated proxy class. * 根据传入的类加载器和接口类数组,生成相应的代理类 */ class<?> cl = getproxyclass0(loader, intfs); /* * invoke its constructor with the designated invocation handler. */ try { if (sm != null) { checknewproxypermission(reflection.getcallerclass(), cl); } //获取构造 final constructor<?> cons = cl.getconstructor(constructorparams); final invocationhandler ih = h; if (!modifier.ispublic(cl.getmodifiers())) { accesscontroller.doexposingd(new privilegedaction<void>() { public void run() { cons.setaccessible(true); return null; } }); } //返回代理对象 return cons.newinstance(new object[]{h}); } catch (illegalaccessexception|instantiationexception e) { throw new internalerror(e.tostring(), e); } }
- 再来看查找/生成的代理类getproxyclass0
/** * generate a proxy class. must call the checkproxyaccess method * to perform permission checks before calling this. */ private static class<?> getproxyclass0(classloader loader, class<?>... interfaces) { if (interfaces.length > 65535) { throw new illegalargumentexception("interface limit exceeded"); } // 如果由实现给定接口的给定加载器定义的代理类存在,将返回缓存的副本; // 否则,它将通过proxyclassfactory创建代理类 return proxyclasscache.get(loader, interfaces); }
/** * a cache of proxy classes * 动态代理类的弱缓存容器 * keyfactory:根据接口的数量,映射一个最佳的key生成函数,其中表示接口的类对象被弱引用; * 也就是key对象被弱引用继承自weakreference(key0、key1、key2、keyx), 保存接口密钥(hash值) * proxyclassfactory:生成动态类的工厂 */ private static final weakcache<classloader, class<?>[], class<?>> proxyclasscache = new weakcache<>(new keyfactory(), new proxyclassfactory());
- weakcache.get(loader, interfaces)
// key 表示缓存键,parameter 表示参数。它的返回值类型为 v,表示缓存值。 public v get(k key, p parameter) { // 判断parameter不能为空 objects.requirenonnull(parameter); expungestaleentries(); object cachekey = cachekey.valueof(key, refqueue); // 该方法将 key 和 refqueue 作为参数调用 cachekey.valueof() 方法,生成一个缓存键 cachekey,并从缓存中获取与该缓存键相关的 valuesmap。 // 如果 valuesmap 不存在,则创建一个新的 concurrenthashmap 对象,并将其加入到缓存中。valuesmap 是一个 concurrentmap 对象,它用于存储缓存键下的子键和值的提供者,其中子键由 subkeyfactory 参数生成。 concurrentmap<object, supplier<v>> valuesmap = map.get(cachekey); if (valuesmap == null) { concurrentmap<object, supplier<v>> oldvaluesmap = map.putifabsent(cachekey, valuesmap = new concurrenthashmap<>()); if (oldvaluesmap != null) { valuesmap = oldvaluesmap; } } // 利用key的工厂类根据key和parameter参数生成键 object subkey = objects.requirenonnull(subkeyfactory.apply(key, parameter)); // 根据该键获取到supplier对象,表示结果的提供者。supplier接口包含了一个get方法 supplier<v> supplier = valuesmap.get(subkey); factory factory = null; while (true) { if (supplier != null) { // supplier可能是一个工厂类实例,或者是一个cachevalue<v>实例 v value = supplier.get(); if (value != null) { return value; } } if (factory == null) { // 核心的创建代理类的原理在factory类里实现 // factory类实际上也是supplier接口的实现类,实现了get方法 factory = new factory(key, parameter, subkey, valuesmap); } if (supplier == null) { supplier = valuesmap.putifabsent(subkey, factory); if (supplier == null) { // 将上面的factory类对象赋值给suppler,在下一次循环时,就可以调用factory类的get方法来生成代理类 supplier = factory; } } else { if (valuesmap.replace(subkey, supplier, factory)) { supplier = factory; } else { // retry with current supplier supplier = valuesmap.get(subkey); } } } }
代码核心逻辑:
factory = new factory(key, parameter, subkey, valuesmap);:// 创建factory对象,factory类是supplier接口的实现类
supplier = factory; // 当缓存中不存在代理类时,将supplier=factory对象
v value = supplier.get(); // 调用factory类的get方法来创建代理类
- factory.get()
public synchronized v get() { v value = null; try { //valuefactory实际上是一个proxyclassfactory实例,调用的是proxyclassfactory.apply方法 value = objects.requirenonnull(valuefactory.apply(key, parameter)); } finally { if (value == null) { valuesmap.remove(subkey, this); } } // wrap value with cachevalue (weakreference) cachevalue<v> cachevalue = new cachevalue<>(value); // put into reversemap reversemap.put(cachevalue, boolean.true); // try replacing us with cachevalue (this should always succeed) if (!valuesmap.replace(subkey, this, cachevalue)) { throw new assertionerror("should not reach here"); } return value; } }
- proxyclassfactory.apply
proxyclassfactory是proxy的静态内部类,apply 用于生成代理类的class对象。
public class<?> apply(classloader loader, class<?>[] interfaces) { map<class<?>, boolean> interfaceset = new identityhashmap<>(interfaces.length); for (class<?> intf : interfaces) { /* * verify that the class loader resolves the name of this interface to the same class object. */ class<?> interfaceclass = null; try { interfaceclass = class.forname(intf.getname(), false, loader); } catch (classnotfoundexception e) { } /* * verify that the class object actually represents an interface. */ if (!interfaceclass.isinterface()) { throw new illegalargumentexception( interfaceclass.getname() + " is not an interface"); } } string proxypkg = null; // package to define proxy class in int accessflags = modifier.public | modifier.final; /* * record the package of a non-public proxy interface so that the * proxy class will be defined in the same package. verify that * all non-public proxy interfaces are in the same package. */ for (class<?> intf : interfaces) { int flags = intf.getmodifiers(); if (!modifier.ispublic(flags)) { accessflags = modifier.final; string name = intf.getname(); int n = name.lastindexof('.'); string pkg = ((n == -1) ? "" : name.substring(0, n + 1)); if (proxypkg == null) { proxypkg = pkg; } else if (!pkg.equals(proxypkg)) { throw new illegalargumentexception( "non-public interfaces from different packages"); } } } if (proxypkg == null) { // if no non-public proxy interfaces, use com.sun.proxy package proxypkg = reflectutil.proxy_package + "."; } /* * choose a name for the proxy class to generate. */ long num = nextuniquenumber.getandincrement(); string proxyname = proxypkg + proxyclassnameprefix + num; /* * generate the specified proxy class. */ byte[] proxyclassfile = proxygenerator.generateproxyclass( proxyname, interfaces, accessflags); return defineclass0(loader, proxyname, proxyclassfile, 0, proxyclassfile.length); }
- proxygenerator.generateproxyclass
generateproxyclass 生成代理类字节码
private byte[] generateclassfile() { //生成hashcode方法 this.addproxymethod(hashcodemethod, object.class); //生成equals方法 this.addproxymethod(equalsmethod, object.class); //生成tostring方法 this.addproxymethod(tostringmethod, object.class); class[] var1 = this.interfaces; int var2 = var1.length; int var3; class var4; for(var3 = 0; var3 < var2; ++var3) { var4 = var1[var3]; method[] var5 = var4.getmethods(); int var6 = var5.length; for(int var7 = 0; var7 < var6; ++var7) { method var8 = var5[var7]; this.addproxymethod(var8, var4); } } iterator var11 = this.proxymethods.values().iterator(); list var12; while(var11.hasnext()) { var12 = (list)var11.next(); checkreturntypes(var12); } iterator var15; try { this.methods.add(this.generateconstructor()); var11 = this.proxymethods.values().iterator(); while(var11.hasnext()) { var12 = (list)var11.next(); var15 = var12.iterator(); while(var15.hasnext()) { proxygenerator.proxymethod var16 = (proxygenerator.proxymethod)var15.next(); this.fields.add(new proxygenerator.fieldinfo(var16.methodfieldname, "ljava/lang/reflect/method;", 10)); this.methods.add(var16.generatemethod()); } } this.methods.add(this.generatestaticinitializer()); } catch (ioexception var10) { throw new internalerror("unexpected i/o exception", var10); } if (this.methods.size() > 65535) { throw new illegalargumentexception("method limit exceeded"); } else if (this.fields.size() > 65535) { throw new illegalargumentexception("field limit exceeded"); } else { this.cp.getclass(dottoslash(this.classname)); this.cp.getclass("java/lang/reflect/proxy"); var1 = this.interfaces; var2 = var1.length; for(var3 = 0; var3 < var2; ++var3) { var4 = var1[var3]; this.cp.getclass(dottoslash(var4.getname())); } this.cp.setreadonly(); bytearrayoutputstream var13 = new bytearrayoutputstream(); dataoutputstream var14 = new dataoutputstream(var13); try { var14.writeint(-889275714); var14.writeshort(0); var14.writeshort(49); this.cp.write(var14); var14.writeshort(this.accessflags); var14.writeshort(this.cp.getclass(dottoslash(this.classname))); var14.writeshort(this.cp.getclass("java/lang/reflect/proxy")); var14.writeshort(this.interfaces.length); class[] var17 = this.interfaces; int var18 = var17.length; for(int var19 = 0; var19 < var18; ++var19) { class var22 = var17[var19]; var14.writeshort(this.cp.getclass(dottoslash(var22.getname()))); } var14.writeshort(this.fields.size()); var15 = this.fields.iterator(); while(var15.hasnext()) { proxygenerator.fieldinfo var20 = (proxygenerator.fieldinfo)var15.next(); var20.write(var14); } var14.writeshort(this.methods.size()); var15 = this.methods.iterator(); while(var15.hasnext()) { proxygenerator.methodinfo var21 = (proxygenerator.methodinfo)var15.next(); var21.write(var14); } var14.writeshort(0); return var13.tobytearray(); } catch (ioexception var9) { throw new internalerror("unexpected i/o exception", var9); } } }
总结
到此这篇关于java动态代理proxy应用和底层源码详细分析的文章就介绍到这了,更多相关java动态代理proxy源码分析内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论