Java JDK动态代理(AOP)的实现原理与使用详析
本文主要给大家介绍了关于java jdk动态代理(aop)实现原理与使用的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍:
一、什么是代理?
代理是一种常用的设计模式,其目的就是为其他对象提供一个代理以控制对某个对象的访问。代理类负责为委托类预处理消息,过滤消息并转发消息,以及进行消息被委托类执行后的后续处理。
代理模式uml图:
简单结构示意图:
为了保持行为的一致性,代理类和委托类通常会实现相同的接口,所以在访问者看来两者没有丝毫的区别。通过代理类这中间一层,能有效控制对委托类对象的直接访问,也可以很好地隐藏和保护委托类对象,同时也为实施不同控制策略预留了空间,从而在设计上获得了更大的灵活性。java 动态代理机制以巧妙的方式近乎完美地实践了代理模式的设计理念。
二、java 动态代理类
java动态代理类位于java.lang.reflect包下,一般主要涉及到以下两个类:
(1)interface invocationhandler:该接口中仅定义了一个方法
publicobject invoke(object obj,method method, object[] args)
在实际使用时,第一个参数obj一般是指代理类,method是被代理的方法,如上例中的request(),args为该方法的参数数组。这个抽象方法在代理类中动态实现。
(2)proxy:该类即为动态代理类,其中主要包含以下内容:
protected proxy(invocationhandler h)
:构造函数,用于给内部的h赋值。
static class getproxyclass (classloaderloader, class[] interfaces)
:获得一个代理类,其中loader是类装载器,interfaces是真实类所拥有的全部接口的数组。
static object newproxyinstance(classloaderloader, class[] interfaces, invocationhandler h)
:返回代理类的一个实例,返回后的代理类可以当作被代理类使用(可使用被代理类的在subject接口中声明过的方法)
所谓dynamicproxy是这样一种class:它是在运行时生成的class,在生成它时你必须提供一组interface给它,然后该class就宣称它实现了这些 interface。你当然可以把该class的实例当作这些interface中的任何一个来用。当然,这个dynamicproxy其实就是一个proxy,它不会替你作实质性的工作,在生成它的实例时你必须提供一个handler,由它接管实际的工作。
在使用动态代理类时,我们必须实现invocationhandler接口
通过这种方式,被代理的对象(realsubject)可以在运行时动态改变,需要控制的接口(subject接口)可以在运行时改变,控制的方式(dynamicsubject类)也可以动态改变,从而实现了非常灵活的动态代理关系。
动态代理步骤:
1.创建一个实现接口invocationhandler的类,它必须实现invoke方法
2.创建被代理的类以及接口
3.通过proxy的静态方法
newproxyinstance(classloaderloader, class[] interfaces, invocationhandler h)
创建一个代理
4.通过代理调用方法
三、jdk的动态代理怎么使用?
1、需要动态代理的接口:
package jiankunking; /** * 需要动态代理的接口 */ public interface subject { /** * 你好 * * @param name * @return */ public string sayhello(string name); /** * 再见 * * @return */ public string saygoodbye(); }
2、需要代理的实际对象
package jiankunking; /** * 实际对象 */ public class realsubject implements subject { /** * 你好 * * @param name * @return */ public string sayhello(string name) { return "hello " + name; } /** * 再见 * * @return */ public string saygoodbye() { return " good bye "; } }
3、调用处理器实现类(有木有感觉这里就是传说中的aop啊)
package jiankunking; import java.lang.reflect.invocationhandler; import java.lang.reflect.method; /** * 调用处理器实现类 * 每次生成动态代理类对象时都需要指定一个实现了该接口的调用处理器对象 */ public class invocationhandlerimpl implements invocationhandler { /** * 这个就是我们要代理的真实对象 */ private object subject; /** * 构造方法,给我们要代理的真实对象赋初值 * * @param subject */ public invocationhandlerimpl(object subject) { this.subject = subject; } /** * 该方法负责集中处理动态代理类上的所有方法调用。 * 调用处理器根据这三个参数进行预处理或分派到委托类实例上反射执行 * * @param proxy 代理类实例 * @param method 被调用的方法对象 * @param args 调用参数 * @return * @throws throwable */ public object invoke(object proxy, method method, object[] args) throws throwable { //在代理真实对象前我们可以添加一些自己的操作 system.out.println("在调用之前,我要干点啥呢?"); system.out.println("method:" + method); //当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用 object returnvalue = method.invoke(subject, args); //在代理真实对象后我们也可以添加一些自己的操作 system.out.println("在调用之后,我要干点啥呢?"); return returnvalue; } }
4、测试
package jiankunking; import java.lang.reflect.invocationhandler; import java.lang.reflect.proxy; /** * 动态代理演示 */ public class dynamicproxydemonstration { public static void main(string[] args) { //代理的真实对象 subject realsubject = new realsubject(); /** * invocationhandlerimpl 实现了 invocationhandler 接口,并能实现方法调用从代理类到委托类的分派转发 * 其内部通常包含指向委托类实例的引用,用于真正执行分派转发过来的方法调用. * 即:要代理哪个真实对象,就将该对象传进去,最后是通过该真实对象来调用其方法 */ invocationhandler handler = new invocationhandlerimpl(realsubject); classloader loader = realsubject.getclass().getclassloader(); class[] interfaces = realsubject.getclass().getinterfaces(); /** * 该方法用于为指定类装载器、一组接口及调用处理器生成动态代理类实例 */ subject subject = (subject) proxy.newproxyinstance(loader, interfaces, handler); system.out.println("动态代理对象的类型:"+subject.getclass().getname()); string hello = subject.sayhello("jiankunking"); system.out.println(hello); // string goodbye = subject.saygoodbye(); // system.out.println(goodbye); } }
5、输出结果如下:
演示demo下载地址:http://xiazai.jb51.net/201707/yuanma/dynamicproxydemo(jb51.net).rar
四、动态代理怎么实现的?
从使用代码中可以看出,关键点在:
subject subject = (subject) proxy.newproxyinstance(loader, interfaces, handler);
通过跟踪提示代码可以看出:当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用。
也就是说,当代码执行到:
subject.sayhello("jiankunking")
这句话时,会自动调用invocationhandlerimpl的invoke方法。这是为啥呢?
=======横线之间的是代码跟分析的过程,不想看的朋友可以直接看结论============
以下代码来自:jdk1.8.0_92
既然生成代理对象是用的proxy类的静态方newproxyinstance,那么我们就去它的源码里看一下它到底都做了些什么?
/** * returns an instance of a proxy class for the specified interfaces * that dispatches method invocations to the specified invocation * handler. * * <p>{@code proxy.newproxyinstance} throws * {@code illegalargumentexception} for the same reasons that * {@code proxy.getproxyclass} does. * * @param loader the class loader to define the proxy class * @param interfaces the list of interfaces for the proxy class * to implement * @param h the invocation handler to dispatch method invocations to * @return a proxy instance with the specified invocation handler of a * proxy class that is defined by the specified class loader * and that implements the specified interfaces * @throws illegalargumentexception if any of the restrictions on the * parameters that may be passed to {@code getproxyclass} * are violated * @throws securityexception if a security manager, <em>s</em>, is present * and any of the following conditions is met: * <ul> * <li> the given {@code loader} is {@code null} and * the caller's class loader is not {@code null} and the * invocation of {@link securitymanager#checkpermission * s.checkpermission} with * {@code runtimepermission("getclassloader")} permission * denies access;</li> * <li> for each proxy interface, {@code intf}, * the caller's class loader is not the same as or an * ancestor of the class loader for {@code intf} and * invocation of {@link securitymanager#checkpackageaccess * s.checkpackageaccess()} denies access to {@code intf};</li> * <li> any of the given proxy interfaces is non-public and the * caller class is not in the same {@linkplain package runtime package} * as the non-public interface and the invocation of * {@link securitymanager#checkpermission s.checkpermission} with * {@code reflectpermission("newproxyinpackage.{package name}")} * permission denies access.</li> * </ul> * @throws nullpointerexception if the {@code interfaces} array * argument or any of its elements are {@code null}, or * if the invocation handler, {@code h}, is * {@code null} */ @callersensitive public static object newproxyinstance(classloader loader, class<?>[] interfaces, invocationhandler h) throws illegalargumentexception { //检查h 不为空,否则抛异常 objects.requirenonnull(h); final class<?>[] intfs = interfaces.clone(); final securitymanager sm = system.getsecuritymanager(); if (sm != null) { checkproxyaccess(reflection.getcallerclass(), loader, intfs); } /* * 获得与指定类装载器和一组接口相关的代理类类型对象 */ class<?> cl = getproxyclass0(loader, intfs); /* * 通过反射获取构造函数对象并生成代理类实例 */ try { if (sm != null) { checknewproxypermission(reflection.getcallerclass(), cl); } //获取代理对象的构造方法(也就是$proxy0(invocationhandler h)) 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; } }); } //生成代理类的实例并把invocationhandlerimpl的实例传给它的构造方法 return cons.newinstance(new object[]{h}); } catch (illegalaccessexception|instantiationexception e) { throw new internalerror(e.tostring(), e); } catch (invocationtargetexception e) { throwable t = e.getcause(); if (t instanceof runtimeexception) { throw (runtimeexception) t; } else { throw new internalerror(t.tostring(), t); } } catch (nosuchmethodexception 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"); } // 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); }
真相还是没有来到,继续,看一下proxyclasscache
/** * a cache of proxy classes */ private static final weakcache<classloader, class<?>[], class<?>> proxyclasscache = new weakcache<>(new keyfactory(), new proxyclassfactory());
奥,原来用了一下缓存啊
那么它对应的get方法啥样呢?
/** * look-up the value through the cache. this always evaluates the * {@code subkeyfactory} function and optionally evaluates * {@code valuefactory} function if there is no entry in the cache for given * pair of (key, subkey) or the entry has already been cleared. * * @param key possibly null key * @param parameter parameter used together with key to create sub-key and * value (should not be null) * @return the cached value (never null) * @throws nullpointerexception if {@code parameter} passed in or * {@code sub-key} calculated by * {@code subkeyfactory} or {@code value} * calculated by {@code valuefactory} is null. */ 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) { //putifabsent这个方法在key不存在的时候加入一个值,如果key存在就不放入 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) { 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); } } } }
我们可以看到它调用了 supplier.get();
获取动态代理类,其中supplier是factory,这个类定义在weakcach的内部。
来瞅瞅,get里面又做了什么?
public synchronized v get() { // serialize access // re-check supplier<v> supplier = valuesmap.get(subkey); if (supplier != this) { // something changed while we were waiting: // might be that we were replaced by a cachevalue // or were removed because of failure -> // return null to signal weakcache.get() to retry // the loop return null; } // else still us (supplier == this) // 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); // try replacing us with cachevalue (this should always succeed) if (valuesmap.replace(subkey, this, cachevalue)) { // put also in reversemap reversemap.put(cachevalue, boolean.true); } else { throw new assertionerror("should not reach here"); } // successfully replaced us with new cachevalue -> return the value // wrapped by it return value; } }
发现重点还是木有出现,但我们可以看到它调用了valuefactory.apply(key, parameter)
方法:
/** * a factory function that generates, defines and returns the proxy class given * the classloader and array of interfaces. */ 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) { 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) { } if (interfaceclass != intf) { throw new illegalargumentexception( intf + " is not visible from class loader"); } /* * verify that the class object actually represents an * interface. */ if (!interfaceclass.isinterface()) { throw new illegalargumentexception( interfaceclass.getname() + " is not an interface"); } /* * verify that this interface is not a duplicate. */ if (interfaceset.put(interfaceclass, boolean.true) != null) { throw new illegalargumentexception( "repeated interface: " + interfaceclass.getname()); } } 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); try { return defineclass0(loader, proxyname, proxyclassfile, 0, proxyclassfile.length); } catch (classformaterror e) { /* * a classformaterror here means that (barring bugs in the * proxy class generation code) there was some other * invalid aspect of the arguments supplied to the proxy * class creation (such as virtual machine limitations * exceeded). */ throw new illegalargumentexception(e.tostring()); } } }
通过看代码终于找到了重点:
//生成字节码 byte[] proxyclassfile = proxygenerator.generateproxyclass(proxyname, interfaces, accessflags);
那么接下来我们也使用测试一下,使用这个方法生成的字节码是个什么样子:
package jiankunking; import sun.misc.proxygenerator; import java.io.file; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.lang.reflect.invocationhandler; import java.lang.reflect.proxy; /** * 动态代理演示 */ public class dynamicproxydemonstration { public static void main(string[] args) { //代理的真实对象 subject realsubject = new realsubject(); /** * invocationhandlerimpl 实现了 invocationhandler 接口,并能实现方法调用从代理类到委托类的分派转发 * 其内部通常包含指向委托类实例的引用,用于真正执行分派转发过来的方法调用. * 即:要代理哪个真实对象,就将该对象传进去,最后是通过该真实对象来调用其方法 */ invocationhandler handler = new invocationhandlerimpl(realsubject); classloader loader = handler.getclass().getclassloader(); class[] interfaces = realsubject.getclass().getinterfaces(); /** * 该方法用于为指定类装载器、一组接口及调用处理器生成动态代理类实例 */ subject subject = (subject) proxy.newproxyinstance(loader, interfaces, handler); system.out.println("动态代理对象的类型:"+subject.getclass().getname()); string hello = subject.sayhello("jiankunking"); system.out.println(hello); // 将生成的字节码保存到本地, createproxyclassfile(); } private static void createproxyclassfile(){ string name = "proxysubject"; byte[] data = proxygenerator.generateproxyclass(name,new class[]{subject.class}); fileoutputstream out =null; try { out = new fileoutputstream(name+".class"); system.out.println((new file("hello")).getabsolutepath()); out.write(data); } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); }finally { if(null!=out) try { out.close(); } catch (ioexception e) { e.printstacktrace(); } } } }
可以看一下这里代理对象的类型:
我们用jd-jui 工具将生成的字节码反编译:
import java.lang.reflect.invocationhandler; import java.lang.reflect.method; import java.lang.reflect.proxy; import java.lang.reflect.undeclaredthrowableexception; import jiankunking.subject; public final class proxysubject extends proxy implements subject { private static method m1; private static method m3; private static method m4; private static method m2; private static method m0; public proxysubject(invocationhandler paraminvocationhandler) { super(paraminvocationhandler); } public final boolean equals(object paramobject) { try { return ((boolean)this.h.invoke(this, m1, new object[] { paramobject })).booleanvalue(); } catch (error|runtimeexception localerror) { throw localerror; } catch (throwable localthrowable) { throw new undeclaredthrowableexception(localthrowable); } } public final string saygoodbye() { try { return (string)this.h.invoke(this, m3, null); } catch (error|runtimeexception localerror) { throw localerror; } catch (throwable localthrowable) { throw new undeclaredthrowableexception(localthrowable); } } public final string sayhello(string paramstring) { try { return (string)this.h.invoke(this, m4, new object[] { paramstring }); } catch (error|runtimeexception localerror) { throw localerror; } catch (throwable localthrowable) { throw new undeclaredthrowableexception(localthrowable); } } public final string tostring() { try { return (string)this.h.invoke(this, m2, null); } catch (error|runtimeexception localerror) { throw localerror; } catch (throwable localthrowable) { throw new undeclaredthrowableexception(localthrowable); } } public final int hashcode() { try { return ((integer)this.h.invoke(this, m0, null)).intvalue(); } catch (error|runtimeexception localerror) { throw localerror; } catch (throwable localthrowable) { throw new undeclaredthrowableexception(localthrowable); } } static { try { m1 = class.forname("java.lang.object").getmethod("equals", new class[] { class.forname("java.lang.object") }); m3 = class.forname("jiankunking.subject").getmethod("saygoodbye", new class[0]); m4 = class.forname("jiankunking.subject").getmethod("sayhello", new class[] { class.forname("java.lang.string") }); m2 = class.forname("java.lang.object").getmethod("tostring", new class[0]); m0 = class.forname("java.lang.object").getmethod("hashcode", new class[0]); return; } catch (nosuchmethodexception localnosuchmethodexception) { throw new nosuchmethoderror(localnosuchmethodexception.getmessage()); } catch (classnotfoundexception localclassnotfoundexception) { throw new noclassdeffounderror(localclassnotfoundexception.getmessage()); } } }
这就是最终真正的代理类,它继承自proxy并实现了我们定义的subject接口
也就是说:
subject subject = (subject) proxy.newproxyinstance(loader, interfaces, handler);
这里的subject实际是这个类的一个实例,那么我们调用它的:
public final string sayhello(string paramstring)
就是调用我们定义的invocationhandlerimpl的 invoke方法:
=======横线之间的是代码跟分析的过程,不想看的朋友可以直接看结论================
五、结论
到了这里,终于解答了:
subject.sayhello("jiankunking")
这句话时,为什么会自动调用invocationhandlerimpl的invoke方法?
因为jdk生成的最终真正的代理类,它继承自proxy并实现了我们定义的subject接口,在实现subject接口方法的内部,通过反射调用了invocationhandlerimpl的invoke方法。
包含生成本地class文件的demo:
http://xiazai.jb51.net/201707/yuanma/dynamicproxydemo2(jb51.net).rar
通过分析代码可以看出java 动态代理,具体有如下四步骤:
- 通过实现 invocationhandler 接口创建自己的调用处理器;
- 通过为 proxy 类指定 classloader 对象和一组 interface 来创建动态代理类;
- 通过反射机制获得动态代理类的构造函数,其唯一参数类型是调用处理器接口类型;
- 通过构造函数创建动态代理类实例,构造时调用处理器对象作为参数被传入。
本文参考过:
//www.jb51.net/kf/201608/533663.html
http://www.ibm.com/developerworks/cn/java/j-lo-proxy1/index.html
好了,以上就是这篇文章的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。
上一篇: 吃柚子上火吗 柚子的功效