朵小喵儿|设计模式之动态代理( 二 )


public static Object newProxyInstance(ClassLoader loader,Class[] interfaces,InvocationHandler h)ClassLoader loader:指定当前目标对象使用的类加载器
Class[] interfaces:目标对象实现的接口的集合 , 使用泛型方式确认类型
InvocationHandler h:指定动态处理器 , 执行目标对象的方法时 , 会触发事件处理器的invoke方法 , 会把当前执行目标对象的方法作为参数传入
public void useJDKProxy() {System.out.println("-------useJDKProxy-------");final UserDao ud = new UserDao();// 生成代理对象IUserDao iud = (IUserDao) Proxy.newProxyInstance(ud.getClass().getClassLoader(),ud.getClass().getInterfaces(),/***因为InvocationHandler是个接口 , 所以可以使用匿名内部类的方式进行实现*/new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("proxy================"+proxy.getClass().getName());//模拟的增强处理Object result = null;result = method.invoke(ud, args);System.out.println(method.getName()+"================"+result);//模拟的增强处理return result;}});iud.save();iud.find();}执行结果:
-------useJDKProxy-------proxy================com.sun.proxy.$Proxy0模拟保存用户save================nullproxy================com.sun.proxy.$Proxy0模拟查找用户find================张三从输出可以看出JDK生成的代理对象名称为:com.sun.proxy.$Proxy0 , 关于动态生成代理的名称 , debug调用栈到Proxy.ProxyClassFactory.apply:
朵小喵儿|设计模式之动态代理以下两行代码就是生成代理对象名称的源码:
private static final String proxyClassNamePrefix = "$Proxy";String proxyName = proxyPkg + proxyClassNamePrefix + num;
朵小喵儿|设计模式之动态代理CGLIB代理JDK实现动态代理需要实现类通过接口定义业务方法 , 对于没有接口的类 , 需要通过CGLib实现动态代理 。
CGLib创建代理对象是通过net.sf.cglib.proxy.Enhancer实现的 , 代理收到方法调用后 , 请求做实际工作的对象是MethodInterceptor 。
public class CglibProxy implements MethodInterceptor {private Object target;public Object getInstance(final Object target) {this.target = target;Enhancer enhancer=new Enhancer();enhancer.setSuperclass(this.target.getClass());//设置目标对象enhancer.setCallback(this);//设置代理拦截器MethodInterceptorreturn enhancer.create();}@Overridepublic Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {System.out.println("obj============="+obj.getClass().getName());//模拟的增强处理System.out.println("method============="+method.getName());System.out.println("proxy============="+proxy.getSignature());Object result=proxy.invokeSuper(obj, args);//目标方法System.out.println("方法执行返回============="+result);//模拟的增强处理return result;}}执行结果:
--------useCGlibProxy--------obj=============proxy.staticProxy.UserDao$$EnhancerByCGLIB$$d229b515method=============saveproxy=============save()V模拟保存用户方法执行返回=============nullobj=============proxy.staticProxy.UserDao$$EnhancerByCGLIB$$d229b515method=============findproxy=============find()Ljava/lang/String;模拟查找用户方法执行返回=============张三