JDK代理:
package com.pinus.factory; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; public class BeanFactory implements InvocationHandler { private static Map<Object, Object> map; private BeanFactory() { } /** * 创建BeanFactory实例 */ public static BeanFactory getInstance() { map = new HashMap<Object, Object>(); return new BeanFactory(); } /** * 得到原类型对象 */ @SuppressWarnings("rawtypes") public Object getBean(Class classType) { try { return classType.newInstance(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 得到代理类型对象 */ @SuppressWarnings("rawtypes") public Object getProxyBean(Class classType) { Object proxyObject = Proxy.newProxyInstance(classType.getClassLoader(), classType.getInterfaces(), this); Object targetObject = this.getBean(classType); map.put(proxyObject.getClass(), targetObject); return proxyObject; } @Override public Object invoke(Object proxyObject, Method method, Object[] args) throws Throwable { return method.invoke(map.get(proxyObject.getClass()), args); } }
CBLIB代理:
package com.pinus.factory; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class BeanFactory implements MethodInterceptor { private static Map<Object, Object> map; private BeanFactory() { } /** * 创建BeanFactory实例 */ public static BeanFactory getInstance() { map = new HashMap<Object, Object>(); return new BeanFactory(); } /** * 得到原类型对象 */ @SuppressWarnings("rawtypes") public Object getBean(Class classType) { try { return classType.newInstance(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 得到代理类型对象 */ @SuppressWarnings("rawtypes") public Object getProxyBean(Class classType) { Object proxyObject; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(classType); enhancer.setCallback(this); proxyObject = enhancer.create(); Object targetObject = this.getBean(classType); map.put(proxyObject.getClass(), targetObject); System.out.println(map.size()); return proxyObject; } @Override public Object intercept(Object proxyObject, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { // TODO Auto-generated method stub return method.invoke(map.get(proxyObject.getClass()), args); } }
总结:JDK代理:动态生成一个类实现目标对象类型所实现的所有接口,将此类实例化后返回
CGLIB代理:动态生成一个类继承目标对象类型,将此类实例化后返回
方法调用:实际上还是调用原目标对象中的方法,动态代理对象并未使用
转载于:https://blog.51cto.com/pinus/1100400