JDK獲取代理對象
1 package isoft.proxy; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 import java.lang.reflect.Proxy; 6 public class JDKProxyFactory implements InvocationHandler{ 7 private Object target;//目標對象 8 9 //單例模式 10 private JDKProxyFactory() {} 11 12 public static JDKProxyFactory getInstance() { 13 return new JDKProxyFactory(); 14 } 15 16 public Object getProxy(Class clazz)throws Exception{ 17 //獲得目標類型的實例對象 18 target = clazz.newInstance(); 19 //根據目標類型對象創建代理對象 20 Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), 21 clazz.getInterfaces(), this); 22 return proxy; 23 } 24 }
CGLIB獲取代理對象
import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class CGLIBProxyFactory implements MethodInterceptor{ private Object target; //目標對象 //單例模式 private CGLIBProxyFactory() {} //無參私有化構造方法 public static CGLIBProxyFactory getInstance() { //獲取唯一實例 return new CGLIBProxyFactory(); } public Object getProxy(Class clazz)throws Exception{ //獲得目標對象的實例對象 target = clazz.newInstance(); Enhancer enhancer =new Enhancer(); enhancer.setSuperclass(clazz); enhancer.setCallback(this); return enhancer.create(); } }