我们都知道AOP的原理就是java的动态代理机制,下面我就对java的动态代理机制进行学习与总结
java动态代理的实现有两个重要的类:
Proxy:类
作用就是用来动态创建一个代理对象的类
InvocationHandler:接口
每一个动态代理类都必须要实现InvocationHandler这个接口,并且每个代理类的实例都关联到了一个handler,当我们通过代理对象调用一个方法的时候,这个方法的调用就会被转发为由InvocationHandler这个接口的 invoke 方法来进行调用。
通过一个例子进行学习与理解:
被代理接口:
package com.zgq.proxy; /** * @author guoqiang.zhao@insentek.com * @date 2016/5/25 * 修正历史: * 2016/5/25:文件创建 */ public interface IStudy { void hello(String str); }
被代理接口的实现类:
package com.zgq.proxy; /** * @author guoqiang.zhao@insentek.com * @date 2016/5/25 * 修正历史: * 2016/5/25:文件创建 */ public class Study implements IStudy { @Override public void hello(String str) { System.out.println("hello:" + str); } }
java动态代理类
package com.zgq.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * @author guoqiang.zhao@insentek.com * @date 2016/5/25 * 修正历史: * 2016/5/25:文件创建 */ public class MyInvocationHandler implements InvocationHandler { private Object object; public MyInvocationHandler (Object object){ this.object = object; } /** * * @param proxy 被代理的对象 * @param method 被代理对象的方法 * @param args 被代理对象方法的参数 * @return * @throws Throwable */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("A==================================="); method.invoke(object,args); System.out.println("B==================================="); return null; } }
测试类:
package com.zgq.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; /** * @author guoqiang.zhao@insentek.com * @date 2016/5/25 * 修正历史: * 2016/5/25:文件创建 */ public class Test { public static void main(String[] args) { Study study = new Study(); InvocationHandler invocationHandler = new MyInvocationHandler(study); //Proxy.newProxyInstance用来动态创建一个代理对象的类 //study.getClass().getClassLoader() 定义代理类的加载器 //study.getClass().getInterfaces() 被代理对象实现的接口 //invocationHandler 代理对象调用方法时会调用实现此类的子类的invoke方法 IStudy iStudy = (IStudy) Proxy.newProxyInstance(study.getClass().getClassLoader(),study.getClass().getInterfaces(),invocationHandler); iStudy.hello("zgq"); } }
执行结果:
A=================================== hello:zgq B=================================== Process finished with exit code 0
通过以上例子对java的动态代理机制有了一定的了解;
IStudy iStudy = (IStudy) Proxy.newProxyInstance(study.getClass().getClassLoader(),study.getClass().getInterfaces(),invocationHandler);
执行这句代码的时候会通过反射机制生成一个代理类,该类实现了IStudy接口,并且重写了接口里面的方法,在该代理类里面有一个InvocationHandler类型的成员变量,也就是调用处理程序,通过调用处理程序来给被代理类增强功能。创建好代理类后就调用类加载器将该类加载到内存,然后再通过反射创建一个该代理类的实例对象。