JDK动态代理的一个例子
1.目标类接口
2.目标类实现类
3.代理对象的拦截器
package com.arvon.jdkproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * 代理对象的拦截器 *@author Huangwen *2017-3-29 */ public class TargetClassInterceptor implements InvocationHandler { private TargetClassImpl targetClassImpl; public TargetClassInterceptor(TargetClassImpl targetClassImpl) { this.targetClassImpl = targetClassImpl; } /** * 生成的代理对象 所实现目标类接口中定义的相关方法的具体实现 */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(">>>>>>before method.invoke(),这里代表代理对象在主业务逻辑方法执行前织入的代码"); method.invoke(targetClassImpl, args); System.out.println(">>>>>>>after method.invoke(),这里代表代理对象在主业务逻辑方法执行后织入的代码"); return null; } }
package com.arvon.jdkproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; /** * 客户端 测试类 *@author Huangwen *2017-3-29 */ public class Client { public static void main(String[] args) { TargetClassImpl targetClassImpl = new TargetClassImpl(); targetClassImpl.mainLogicMethod(); System.out.println("===================================="); InvocationHandler h = new TargetClassInterceptor(targetClassImpl); /** * 以下代码会生成一个$Proxy对象,该对象实现了ITargetClass,具体的方法体就是InvocationHandler里面的invoke方法。 */ ITargetClass proxyInstance =(ITargetClass) Proxy.newProxyInstance(targetClassImpl.getClass().getClassLoader(), targetClassImpl.getClass().getInterfaces(), h); proxyInstance.mainLogicMethod(); } }
5.打印的结果
理解Jdk动态代理的原理是理解spring aop 原理的前提。