本篇文章代码内容较多,讲的可能会有些粗糙,大家可以选择性阅读。
本篇文章的目的是简单的分析动态代理的原理及模仿
jdk proxy
手写一个动态代理以及对几种代理做一个总结。
对于代理模式的介绍和讲解,网上已经有很多优质的文章,我这里就不会再过多的介绍了,这里推荐几篇优质的文章作为参考:
另外,我的 github 仓库对应目录中也有相关的基础示例代码:https://github.com/eamonzzz/java-advanced...
动态代理的概念这里就不再阐述了;动态代理相对于静态代理来说,它的功能更加强大,随着业务的扩展,适应性更强。
在说动态代理原理之前,我们还是来看看动态代理的一般使用。
本篇文章的使用示例,是以一个最为简单的代理模式的代码为例,相信大家在学习或了解代理模式的时候都有看到或者接触过这些代码。
subject
主体抽象接口:/** * @author eamon.zhang * @date 2019-10-09 下午4:06 */ public interface subject { void request(); }
realsubject
来处理我们的真实的逻辑:/** * @author eamon.zhang * @date 2019-10-09 下午4:06 */ public class realsubject implements subject { @override public void request() { system.out.println("真实处理逻辑!"); } }
realsubject
类的情况下,如果我们要实现在执行realsubject
类中request()
方法之前或之后执行一段逻辑的话,该怎么实现呢?这就得创建一个代理类,来达到增强原有代码的目的。所以现在创建一个 jdk 动态代理类 realsubjectjdkdynamicproxy
:/** * @author eamon.zhang * @date 2019-10-09 下午4:08 */ public class realsubjectjdkdynamicproxy implements invocationhandler { // 被代理对象的引用 private object target; // 通过构造器传入对象引用 public realsubjectjdkdynamicproxy(object target) { this.target = target; } // 获得 jdk 动态代理创建的代理对象 public object getinstance() { class<?> clazz = target.getclass(); return proxy.newproxyinstance(clazz.getclassloader(), clazz.getinterfaces(), this); } @override public object invoke(object o, method method, object[] objects) throws throwable { before(); // 代理执行被代理对象的相应方法 object invoke = method.invoke(target, objects); after(); return invoke; } private void before() { system.out.println("前置增强!"); } private void after() { system.out.println("后置增强!"); } }
@test public void test(){ subject realsubject = new realsubject(); realsubjectjdkdynamicproxy proxy = new realsubjectjdkdynamicproxy(realsubject); subject instance = (subject) proxy.getinstance(); instance.request(); system.out.println(realsubject.getclass()); system.out.println(instance.getclass()); }
前置增强! 真实处理逻辑! 后置增强! class com.eamon.javadesignpatterns.proxy.dynamic.jdk.realsubject class com.sun.proxy.$proxy8
从结果来看,上面的代码已经达到了我们的增强的目的。
不知道大家有没有注意到上面的测试代码中,最后两行我将代理之前和代理之后的class
对象给打印了出来;并且发现,这两个对象并非同一个,最重要的是,经过代理之后的对象的subject
是com.sun.proxy.$proxy8
而不是com.eamon.javadesignpatterns.proxy.dynamic.jdk.realsubject
或者com.eamon.javadesignpatterns.proxy.dynamic.jdk.subject
,那么这个instance
到底是从哪里来?带着这个疑问,我们来通过 jdk proxy 源码来分析一下:
我们跟进realsubjectjdkdynamicproxy
类中的proxy.newproxyinstance(clazz.getclassloader(), clazz.getinterfaces(), this);
方法:
public static object newproxyinstance(classloader loader, class<?>[] interfaces, invocationhandler h) throws illegalargumentexception { objects.requirenonnull(h); 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 { ... final constructor<?> cons = cl.getconstructor(constructorparams); final invocationhandler ih = h; if (!modifier.ispublic(cl.getmodifiers())) { accesscontroller.doprivileged(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); } ... }
发现在newproxyinstance
方法中调用了getproxyclass0(loader, intfs)
方法,我们跟进去这个方法看一下:
/** * 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"); } // if the proxy class defined by the given loader implementing // the given interfaces exists, this will simply return the cached copy; // otherwise, it will create the proxy class via the proxyclassfactory return proxyclasscache.get(loader, interfaces); }
代码逻辑很简单,做了两个事情:
65535
,接口个数用 2 个 byte
存储,最大支持 65535
个。proxyclasscache
缓存中去取,从注释中可知,如果缓存没有就会调用proxyclassfactory
去创建。我们现在就来简单分析一下proxyclasscache.get(loader, interfaces)
里面的逻辑:
public v get(k key, p parameter) { objects.requirenonnull(parameter); expungestaleentries(); object cachekey = cachekey.valueof(key, refqueue); // lazily install the 2nd level valuesmap for the particular cachekey 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; } } // create subkey and retrieve the possible supplier<v> stored by that // subkey from valuesmap object subkey = objects.requirenonnull(subkeyfactory.apply(key, parameter)); supplier<v> supplier = valuesmap.get(subkey); factory factory = null; // 这里是一个 while(true) while (true) { // 如果创建 factory(这里指proxyclassfactory) 成功,就调用 factory.get()方法 if (supplier != null) { // supplier might be a factory or a cachevalue<v> instance // v value = supplier.get(); if (value != null) { return value; } } // else no supplier in cache // or a supplier that returned null (could be a cleared cachevalue // or a factory that wasn't successful in installing the cachevalue) // lazily construct a factory if (factory == null) { factory = new factory(key, parameter, subkey, valuesmap); } if (supplier == null) { supplier = valuesmap.putifabsent(subkey, factory); if (supplier == null) { // successfully installed factory supplier = factory; } // else retry with winning supplier } else { if (valuesmap.replace(subkey, supplier, factory)) { // successfully replaced // cleared cacheentry / unsuccessful factory // with our factory supplier = factory; } else { // retry with current supplier supplier = valuesmap.get(subkey); } } } }
代码可能有点长,其实逻辑就是为了调用proxyclassfactory.apply()
去生成代理类。我们从while(true)
处将代码分割成两个部分来看:
proxyclassfactory
,如果创建成功了,则可以取到(缓存中的 key 这里不分析了)while(true)
代码块中的逻辑,if (supplier != null)
这个判断,如果缓存中创建了proxyclassfactory
就会执行supplier.get()
并且终止循环;如果没有,则会执行new factory(key, parameter, subkey, valuesmap);
去创建factory
,然后将其放入缓存supplier
中,然后继续循环,这个时候就会执行if (supplier != null)
代码块中的逻辑,我们再来分析一下这个代码块里面的代码:if (supplier != null) { // supplier might be a factory or a cachevalue<v> instance v value = supplier.get(); if (value != null) { return value; } }
跟进 supplier.get()
方法去看一下,我们从上面的分析可以知道这里的supplier
其实就是一个factory
,所以我们看factory
的实现,重点看get()
方法:
private final class factory implements supplier<v> { ... @override public synchronized v get() { // serialize access ... // create new value v value = null; try { value = objects.requirenonnull(valuefactory.apply(key, parameter)); } finally { if (value == null) { // remove us on failure valuesmap.remove(subkey, this); } } // the only path to reach here is with non-null value assert value != null; // 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"); } // successfully replaced us with new cachevalue -> return the value // wrapped by it return value; } }
我们注意到,代码中的重点是在objects.requirenonnull(valuefactory.apply(key, parameter));
,那这个代码中的valuefactory
是什么呢?我们在proxy
中,来看一下proxyclasscache
的定义
private static final weakcache<classloader, class<?>[], class<?>> proxyclasscache = new weakcache<>(new keyfactory(), new proxyclassfactory());
weakcache
中第二个参数是new proxyclassfactory()
,再来看一下对应的构造器:
public weakcache(bifunction<k, p, ?> subkeyfactory, bifunction<k, p, v> valuefactory) { this.subkeyfactory = objects.requirenonnull(subkeyfactory); this.valuefactory = objects.requirenonnull(valuefactory); }
这时候明白了吗?其实 valuefactory
就是proxyclassfactory()
明白了这一点,就来分析一下valuefactory.apply(key, parameter)
到底执行了什么?我们直接看proxyclassfactory
的代码
private static final class proxyclassfactory implements bifunction<classloader, class<?>[], class<?>> { // prefix for all proxy class names private static final string proxyclassnameprefix = "$proxy"; // next number to use for generation of unique proxy class names private static final atomiclong nextuniquenumber = new atomiclong(); @override public class<?> apply(classloader loader, class<?>[] interfaces) { ... /* * generate the specified proxy class. */ byte[] proxyclassfile = proxygenerator.generateproxyclass( proxyname, interfaces, accessflags); try { return defineclass0(loader, proxyname, proxyclassfile, 0, proxyclassfile.length); } catch (classformaterror e) { throw new illegalargumentexception(e.tostring()); } } }
纵观全览,不难分析,代码中其实就是在创建$proxy
这个中间代理类,其中byte[] proxyclassfile
是代码块中组装完成之后的类的字节码文件数据,通过proxygenerator.generateproxyclass()
生成;然后通过classloader
动态加载字节码,并生成动态代理类的class
实例,并返回。
我们再跟进proxygenerator.generateproxyclass()
方法,来看看在生成代理类过程中的处理逻辑,看重点代码:。
public static byte[] generateproxyclass(final string var0, class<?>[] var1, int var2) { proxygenerator var3 = new proxygenerator(var0, var1, var2); final byte[] var4 = var3.generateclassfile(); ... return var4; }
可以发现其代码调用了var3.generateclassfile()
去生成class
文件,所以我们跟进generateclassfile()
方法,看重点内容:
private byte[] generateclassfile() { this.addproxymethod(hashcodemethod, object.class); this.addproxymethod(equalsmethod, object.class); 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); } } ... }
代码有点长,这里就不全部展开了,有兴趣的朋友可以跟进去详细看一下。从代码中我们大致可以看出来,在生成代理类的过程中,还添加了hashcode、equals、tostring
这三个方法,然后后面的逻辑就是将代理对象中的所有接口进行迭代,将其所有的方法都重新生成代理方法;然后生成字节码。
最后再将代理类加载到jvm
中。
jdk proxy
生成的代理类$proxy
我们通过下面这段代码,将$proxy
文件输出到文件:
@test public void test1(){ system.getproperties().put("sun.misc.proxygenerator.savegeneratedfiles", "true"); realsubject realsubject = new realsubject(); realsubjectjdkdynamicproxy proxy = new realsubjectjdkdynamicproxy(realsubject); subject instance = (subject) proxy.getinstance(); try { byte[] proxychar= proxygenerator.generateproxyclass("$proxy0", new class[]{subject.class}); outputstream outputstream = new fileoutputstream("/users/eamon.zhang/ideaprojects/own/java-advanced/01.designpatterns/design-patterns/"+instance.getclass().getsimplename()+".class"); outputstream.write(proxychar); outputstream.flush(); outputstream.close(); } catch (ioexception e) { e.printstacktrace(); } instance.request(); system.out.println(instance.getclass()); }
通过idea
工具查看$proxy0
,印证一下我们之前的分析:
public final class $proxy0 extends proxy implements subject { private static method m1; private static method m2; private static method m3; private static method m0; public $proxy0(invocationhandler var1) throws { super(var1); } public final boolean equals(object var1) throws { try { return (boolean)super.h.invoke(this, m1, new object[]{var1}); } catch (runtimeexception | error var3) { throw var3; } catch (throwable var4) { throw new undeclaredthrowableexception(var4); } } public final string tostring() throws { try { return (string)super.h.invoke(this, m2, (object[])null); } catch (runtimeexception | error var2) { throw var2; } catch (throwable var3) { throw new undeclaredthrowableexception(var3); } } public final void request() throws { try { super.h.invoke(this, m3, (object[])null); } catch (runtimeexception | error var2) { throw var2; } catch (throwable var3) { throw new undeclaredthrowableexception(var3); } } public final int hashcode() throws { try { return (integer)super.h.invoke(this, m0, (object[])null); } catch (runtimeexception | error var2) { throw var2; } catch (throwable var3) { throw new undeclaredthrowableexception(var3); } } static { try { m1 = class.forname("java.lang.object").getmethod("equals", class.forname("java.lang.object")); m2 = class.forname("java.lang.object").getmethod("tostring"); m3 = class.forname("com.eamon.javadesignpatterns.proxy.dynamic.jdk.subject").getmethod("request"); m0 = class.forname("java.lang.object").getmethod("hashcode"); } catch (nosuchmethodexception var2) { throw new nosuchmethoderror(var2.getmessage()); } catch (classnotfoundexception var3) { throw new noclassdeffounderror(var3.getmessage()); } } }
总结一下jdk proxy
的实现步骤:
jdk proxy
类重新生成一个新的类,同时新的类要实现被代理类的所有实现的接口,还有hashcode、equals、tostring
这三个方法java
代码,把新加的业务逻辑方法由一定的逻辑代码去调用(在代码中体现)java
代码的 .class
文件jvm
中运行在明白了上面的原理之后,其实我们就可以尝试手动来实现一个jdk proxy
:
我们参照jdk proxy
实现原理分析一下需要动手编写哪些内容:
mimeproxy
newproxyinstance(clazz.getclassloader(), clazz.getinterfaces(), this)
这一个方法,方法参数为:(classloader loader,class<?>[] interfaces,invocationhandler h)
,所以我们需要创建一个classloader
、invocationhandler
;下面来一步一步创建:
mimeclassloader
类,继承自classloader
,并重写findclass()
方法:/** * @author eamon.zhang * @date 2019-10-10 下午2:47 */ public class mimeclassloader extends classloader { private object target; public mimeclassloader(object target) { this.target = target; } @override protected class<?> findclass(string name) throws classnotfoundexception { string classname = target.getclass().getpackage().getname() + "." + name; string filepath = mimeclassloader.class.getresource("").getpath() + name + ".class"; try { uri uri = new uri("file:///" + filepath); path path = paths.get(uri); file file = path.tofile(); if (file.exists()) { byte[] filebytes = files.readallbytes(path); return defineclass(classname, filebytes, 0, filebytes.length); } } catch (exception e) { e.printstacktrace(); } return null; } }
mimeinvocationhandler
类:/** * @author eamon.zhang * @date 2019-10-10 下午2:46 */ public interface mimeinvocationhandler { public object invoke(object proxy, method method, object[] args) throws throwable; }
mimeproxy
类,这个类就是用来组装成代理类,并加载到jvm
,然后返回这个代理对象:/** * @author eamon.zhang * @date 2019-10-10 下午3:08 */ public class mimeproxy { private static final string ln = "\r\n"; private static final string semi = ";"; private static map<class, class> mappings = new hashmap<class, class>(); static { mappings.put(int.class, integer.class); } public static object newproxyinstance(mimeclassloader loader, class<?>[] interfaces, mimeinvocationhandler h) throws illegalargumentexception { try { // 1. 动态生成 .java 文件 string src = generatesrc(interfaces); // system.out.println(src); // 2. java 文件输出到磁盘 string filepath = mimeproxy.class.getresource("").getpath(); // system.out.println(filepath); file f = new file(filepath + "$proxy8.java"); // f.deleteonexit(); filewriter fw = new filewriter(f); fw.write(src); fw.flush(); fw.close(); // 3. 把 java 文件编译成 .class 文件 javacompiler compiler = toolprovider.getsystemjavacompiler(); standardjavafilemanager sjfm = compiler.getstandardfilemanager(null, null, null); iterable<? extends javafileobject> iterable = sjfm.getjavafileobjects(f); javacompiler.compilationtask task = compiler.gettask(null, sjfm, null, null, null, iterable); task.call(); sjfm.close(); // 4. 把.class 文件加载到jvm class<?> proxyclass = loader.findclass("$proxy8"); constructor<?> c = proxyclass.getconstructor(mimeinvocationhandler.class); f.delete(); // 5. 返回字节码重组以后的新的代理对象 return c.newinstance(h); } catch (exception e) { e.printstacktrace(); } return null; } /** * 生成 代理类 * * @param interfaces * @return */ private static string generatesrc(class<?>[] interfaces) { // 这里使用 stringbuffer 线程安全 stringbuffer sb = new stringbuffer(); sb.append("package ").append(interfaces[0].getpackage().getname()).append(semi).append(ln); sb.append("import ").append(interfaces[0].getname()).append(semi).append(ln); sb.append("import java.lang.reflect.*;").append(ln); sb.append("import ").append(interfaces[0].getpackage().getname()).append(".mimeproxy.mimeinvocationhandler;").append(ln); sb.append("public class $proxy8 implements ").append(interfaces[0].getsimplename()).append(" {").append(ln); sb.append("mimeinvocationhandler h;" + ln); sb.append("public $proxy8(mimeinvocationhandler h) {").append(ln); sb.append("this.h = h;").append(ln); sb.append("}").append(ln); for (method method : interfaces[0].getmethods()) { class<?>[] params = method.getparametertypes(); stringbuffer paramnames = new stringbuffer(); stringbuffer paramvalues = new stringbuffer(); stringbuffer paramclasses = new stringbuffer(); for (class<?> clazz : params) { string type = clazz.getname(); string paramname = tolowerfirstcase(clazz.getsimplename()); paramnames.append(type).append(" ").append(paramname); paramvalues.append(paramname); paramclasses.append(clazz.getname()).append(".class"); for (int i = 0; i < params.length; i++) { paramnames.append(","); paramvalues.append(","); paramclasses.append(","); } } sb.append("public ").append(method.getreturntype().getname()).append(" ").append(method.getname()) .append("(").append(paramnames.tostring()).append(") {").append(ln); sb.append("try {").append(ln); // method m = interfaces[0].getname().class.getmethod(method.getname()),new class[]{paramclasses.tostring()}); sb.append("method m = ").append(interfaces[0].getname()).append(".class.getmethod(\"") .append(method.getname()).append("\", new class[]{").append(paramclasses.tostring()).append("});") .append(ln); // return this.h.invoke(this, m, new object[]{paramvalues}, method.getreturntype()); sb.append(hasreturnvalue(method.getreturntype()) ? "return " : "") .append(getcasecode("this.h.invoke(this,m,new object[]{" + paramvalues + "})", method.getreturntype())) .append(";") .append(ln); sb.append("} catch (error _ex) {}").append(ln); sb.append("catch (throwable e) {").append(ln); sb.append("throw new undeclaredthrowableexception(e);").append(ln); sb.append("}"); sb.append(getreturnemptycode(method.getreturntype())).append(ln); sb.append("}"); } sb.append("}").append(ln); return sb.tostring(); } /** * 获取返回值类型 * * @param returnclass * @return */ private static string getreturnemptycode(class<?> returnclass) { if (mappings.containskey(returnclass)) { return "return 0;"; } else if (returnclass == void.class) { return ""; } else { return "return null;"; } } /** * 拼接 invocationhandler 执行代码 * * @param code * @param returnclass * @return */ private static string getcasecode(string code, class<?> returnclass) { if (mappings.containskey(returnclass)) { return "((" + mappings.get(returnclass).getname() + ")" + code + ")." + returnclass.getsimplename() + "value()"; } return code; } /** * 判断是否有返回值 * * @param clazz * @return */ private static boolean hasreturnvalue(class<?> clazz) { return clazz != void.class; } /** * 首字母转换为小写 * * @param src * @return */ private static string tolowerfirstcase(string src) { char[] chars = src.tochararray(); chars[0] += 32; return string.valueof(chars); } }
这样子就编写了一个属于自己的动态代理,当然,代理方法还不完善,只是针对本示例进行了编写,有兴趣的朋友可以试试将其改为更通用的代码。
下面来看一下 cglib 的动态代理的使用
先创建realsubject
类,注意,这个类不用实现任何接口:
/** * @author eamon.zhang * @date 2019-10-09 下午4:22 */ public class realsubject { public void request(){ system.out.println("真实处理逻辑!"); } }
然后创建realsubjectcglibdynamicproxy
代理类,它必须实现methodinterceptor
接口:
/** * @author eamon.zhang * @date 2019-10-09 下午4:23 */ public class realsubjectcglibdynamicproxy implements methodinterceptor { public object getinstance(class<?> clazz) { // 通过cglib动态代理获取代理对象的过程 enhancer enhancer = new enhancer(); // 要把哪个设置为即将生成的新类父类 enhancer.setsuperclass(clazz); // 设置回调对象 enhancer.setcallback(this); // 创建代理对象 return enhancer.create(); } @override public object intercept(object obj, method method, object[] args, methodproxy proxy) throws throwable { before(); object invokesuper = proxy.invokesuper(obj, args); after(); return invokesuper; } private void before() { system.out.println("前置增强!"); } private void after() { system.out.println("后置增强!"); } }
这样,一个简单的cglib
动态代理实现就完成了,我们现在来创建测试代码:
@test public void test(){ realsubjectcglibdynamicproxy proxy = new realsubjectcglibdynamicproxy(); realsubject instance = (realsubject) proxy.getinstance(realsubject.class); instance.request(); }
测试结果:
前置增强! 真实处理逻辑! 后置增强!
不管是jdk proxy
还是cglib
,他们的核心内容都是去创建代理类,所以我们只要去了解其创建代理类的过程就 ok 了。
从上面简单的使用示例可以知道,要使用 cglib 动态代理,代理类必须要实现methodinterceptor
(方法拦截器),methodinterceptor
接口源码如下:
/** * general-purpose {@link enhancer} callback which provides for "around advice". * @author juozas baliuka <a href="mailto:baliuka@mwm.lt">baliuka@mwm.lt</a> * @version $id: methodinterceptor.java,v 1.8 2004/06/24 21:15:20 herbyderby exp $ */ public interface methodinterceptor extends callback { /** * all generated proxied methods call this method instead of the original method. * the original method may either be invoked by normal reflection using the method object, * or by using the methodproxy (faster). * @param obj "this", the enhanced object * @param method intercepted method * @param args argument array; primitive types are wrapped * @param proxy used to invoke super (non-intercepted method); may be called * as many times as needed * @throws throwable any exception may be thrown; if so, super method will not be invoked * @return any value compatible with the signature of the proxied method. method returning void will ignore this value. * @see methodproxy */ public object intercept(object obj, java.lang.reflect.method method, object[] args, methodproxy proxy) throws throwable; }
接口中只有一个intercept
方法,其中传入的参数:
obj
表示增强的对象,即实现这个接口类的一个对象;method
表示要被拦截的方法;args
表示方法参数;proxy
表示要触发父类的方法对象;在创建代理对象的逻辑getinstance(class<?> clazz)
中,调用了enhancer.create()
方法,我们跟进源码看一下:
/** * generate a new class if necessary and uses the specified * callbacks (if any) to create a new object instance. * uses the no-arg constructor of the superclass. * @return a new instance */ public object create() { classonly = false; argumenttypes = null; return createhelper(); }
源码注释内容翻译:如有必要,生成一个新类,并使用指定的回调(如果有)来创建一个新的对象实例。 使用的父类的参数的构造方法来实例化父类。
它的核心内容是在createhelper();
方法中:
private object createhelper() { prevalidate(); object key = key_factory.newinstance((superclass != null) ? superclass.getname() : null, reflectutils.getnames(interfaces), filter == all_zero ? null : new weakcachekey<callbackfilter>(filter), callbacktypes, usefactory, interceptduringconstruction, serialversionuid); this.currentkey = key; object result = super.create(key); return result; }
prevalidate()
方法的作用是,前置校验,校验callbacktypes、filter
是否为空,以及为空时的处理。
然后通过key_factory.newinstance()
方法创建enhancerkey
对象,并将其作为super.create(key)
方法的参数传入,我们来看一下这个create()
方法,发现它是enhancer
类的父类abstractclassgenerator
中的一个方法:
protected object create(object key) { try { classloader loader = getclassloader(); map<classloader, classloaderdata> cache = cache; classloaderdata data = cache.get(loader); if (data == null) { synchronized (abstractclassgenerator.class) { cache = cache; data = cache.get(loader); if (data == null) { map<classloader, classloaderdata> newcache = new weakhashmap<classloader, classloaderdata>(cache); data = new classloaderdata(loader); newcache.put(loader, data); cache = newcache; } } } this.key = key; object obj = data.get(this, getusecache()); if (obj instanceof class) { return firstinstance((class) obj); } return nextinstance(obj); } catch (runtimeexception e) { throw e; } catch (error e) { throw e; } catch (exception e) { throw new codegenerationexception(e); } }
这个方法在最后调用了 nextinstance(obj)
方法,它对应的实现,是在enhancer
类中:
protected object nextinstance(object instance) { enhancerfactorydata data = (enhancerfactorydata) instance; if (classonly) { return data.generatedclass; } class[] argumenttypes = this.argumenttypes; object[] arguments = this.arguments; if (argumenttypes == null) { argumenttypes = constants.empty_class_array; arguments = null; } return data.newinstance(argumenttypes, arguments, callbacks); }
这里又调用了data.newinstance(argumenttypes, arguments, callbacks)
方法,第一个参数为代理对象的构造器类型,第二个为代理对象构造方法参数,第三个为对应回调对象。源码如下:
public object newinstance(class[] argumenttypes, object[] arguments, callback[] callbacks) { setthreadcallbacks(callbacks); try { // explicit reference equality is added here just in case arrays.equals does not have one if (primaryconstructorargtypes == argumenttypes || arrays.equals(primaryconstructorargtypes, argumenttypes)) { // if we have relevant constructor instance at hand, just call it // this skips "get constructors" machinery return reflectutils.newinstance(primaryconstructor, arguments); } // take a slow path if observing unexpected argument types return reflectutils.newinstance(generatedclass, argumenttypes, arguments); } finally { // clear thread callbacks to allow them to be gc'd setthreadcallbacks(null); } }
我们发现这里面的逻辑的意思就是,根据传进来的参数,通过反射来生成对象,我们可以利用cglib
的代理类可以将内存中的 class
文件写入本地磁盘:
@test public void test1(){ //利用 cglib 的代理类可以将内存中的 class 文件写入本地磁盘 system.setproperty(debuggingclasswriter.debug_location_property, "/users/eamon.zhang/documents/cglib"); realsubjectcglibdynamicproxy proxy = new realsubjectcglibdynamicproxy(); realsubject instance = (realsubject) proxy.getinstance(realsubject.class); instance.request(); }
执行之后,在对应的目录中可以看到生成了下图中这三个.class
文件:
通过调试跟踪,我们发现 realsubject$$enhancerbycglib$$5389cdca
就是 cglib
生成的代理类,继承了 realsubject
类。通过idea
查看该源码:
public class realsubject$$enhancerbycglib$$5389cdca extends realsubject implements factory { ... static void cglib$statichook1() { cglib$thread_callbacks = new threadlocal(); cglib$emptyargs = new object[0]; class var0 = class.forname("com.eamon.javadesignpatterns.proxy.dynamic.cglib.realsubject$$enhancerbycglib$$5389cdca"); class var1; cglib$request$0$method = reflectutils.findmethods(new string[]{"request", "()v"}, (var1 = class.forname("com.eamon.javadesignpatterns.proxy.dynamic.cglib.realsubject")).getdeclaredmethods())[0]; cglib$request$0$proxy = methodproxy.create(var1, var0, "()v", "request", "cglib$request$0"); method[] var10000 = reflectutils.findmethods(new string[]{"equals", "(ljava/lang/object;)z", "tostring", "()ljava/lang/string;", "hashcode", "()i", "clone", "()ljava/lang/object;"}, (var1 = class.forname("java.lang.object")).getdeclaredmethods()); cglib$equals$1$method = var10000[0]; cglib$equals$1$proxy = methodproxy.create(var1, var0, "(ljava/lang/object;)z", "equals", "cglib$equals$1"); cglib$tostring$2$method = var10000[1]; cglib$tostring$2$proxy = methodproxy.create(var1, var0, "()ljava/lang/string;", "tostring", "cglib$tostring$2"); cglib$hashcode$3$method = var10000[2]; cglib$hashcode$3$proxy = methodproxy.create(var1, var0, "()i", "hashcode", "cglib$hashcode$3"); cglib$clone$4$method = var10000[3]; cglib$clone$4$proxy = methodproxy.create(var1, var0, "()ljava/lang/object;", "clone", "cglib$clone$4"); } final void cglib$request$0() { super.request(); } public final void request() { methodinterceptor var10000 = this.cglib$callback_0; if (var10000 == null) { cglib$bind_callbacks(this); var10000 = this.cglib$callback_0; } if (var10000 != null) { var10000.intercept(this, cglib$request$0$method, cglib$emptyargs, cglib$request$0$proxy); } else { super.request(); } } ... }
我们通过代理类的源码可以看到,代理类会获得所有在父类继承来的方法,并且会有 methodproxy
与之对应,比如 method cglib$request$0$method
、methodproxy cglib$request$0$proxy
这些方法在代理类的 reuqest()
中都有调用。
调用过程: 代理对象调用 this.request()
方法 -> 调用拦截器 -> methodproxy.invokesuper
-> cglib$request$0()
-> 被代理对象 request()
方法。 此时,我们发现拦截器 methodinterceptor
中就是由 methodproxy
的 invokesuper
方法调用代理方法的。
methodproxy 非常关键,我们分析一下它具体做了什么:
public class methodproxy { private signature sig1; private signature sig2; private createinfo createinfo; private final object initlock = new object(); private volatile fastclassinfo fastclassinfo; /** * for internal use by {@link enhancer} only; see the {@link net.sf.cglib.reflect.fastmethod} class * for similar functionality. */ public static methodproxy create(class c1, class c2, string desc, string name1, string name2) { methodproxy proxy = new methodproxy(); proxy.sig1 = new signature(name1, desc); proxy.sig2 = new signature(name2, desc); proxy.createinfo = new createinfo(c1, c2); return proxy; } ... private static class createinfo { class c1; class c2; namingpolicy namingpolicy; generatorstrategy strategy; boolean attemptload; public createinfo(class c1, class c2) { this.c1 = c1; this.c2 = c2; abstractclassgenerator fromenhancer = abstractclassgenerator.getcurrent(); if (fromenhancer != null) { namingpolicy = fromenhancer.getnamingpolicy(); strategy = fromenhancer.getstrategy(); attemptload = fromenhancer.getattemptload(); } } } ...
继续看invokesuper()
方法:
public object invokesuper(object obj, object[] args) throws throwable { try { init(); fastclassinfo fci = fastclassinfo; return fci.f2.invoke(fci.i2, obj, args); } catch (invocationtargetexception e) { throw e.gettargetexception(); } } private static class fastclassinfo { fastclass f1; fastclass f2; int i1; int i2; }
上面代码调用过程就是获取到代理类对应的 fastclass
,并执行了代理方法。还记得之前生成三个 class
文件吗?realsubject$$enhancerbycglib$$5389cdca$$fastclassbycglib$$57b94d72.class
就是代理类的 fastclass
,realsubject$$fastclassbycglib$$ed23432.class
就是被代理类的fastclass
。
cglib
动态代理执行代理方法效率之所以比 jdk
的高是因为 cglib
采用了 fastclass
机 制,它的原理简单来说就是:
index(int 类型)
。这个 index
当做一个入参,fastclass
就可以直接定位要调用的方法直接进行调用,这样省去了反射调用,所以调用效率比 jdk
动态代理通过反射调用高。至此,cglib 动态代理的原理我们就基本搞清楚了,如果对代码细节有兴趣的小伙伴可以再自行深入研究。
jdk
动态代理是实现了被代理对象的接口,cglib
是继承了被代理对象。jdk
和 cglib
都是在运行期生成字节码,jdk
是直接写 class
字节码,cglib
使用 asm
框架写 class
字节码,cglib
代理实现更复杂,生成代理类 比 jdk
效率低。jdk
调用代理方法,是通过反射机制调用,cglib
是通过 fastclass
机制直接调用方法, cglib
执行效率 更高bean
有实现接口时,spring
就会用 jdk
的动态代理bean
没有实现接口时,spring
选择 cglib
。spring
可以通过配置强制使用 cglib
,只需在 spring
的配置文件中加入如下代码:<aop:aspectj-autoproxy proxy-target-class="true"/>
参考资料:https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html
本篇文章的源码目录:https://github.com/eamonzzz/java-advanced/tree/master/01.designpatterns/design-patterns/src/main/java/com/eamon/javadesignpatterns/proxy
测试类源码目录:https://github.com/eamonzzz/java-advanced/tree/master/01.designpatterns/design-patterns/src/test/java/com/eamon/javadesignpatterns/proxy
欢迎大家 star 源码,共同进步,我会按照 git 上的大纲在学习的同时,记录文章与源码~
博主刚开始写博客不久,文中若有错误或者有任何的建议,请在留言中指出,向大家学习~
本文由博客一文多发平台 openwrite 发布!
如对本文有疑问, 点击进行留言回复!!
设计模式之单例模式(Singleton Pattern),太简单了
java多线程定时器和java判断一个时间是否在时间区间内和用正则表达式获取String字符串之间的数据
网友评论