1. 程式人生 > >獲取動態代理物件

獲取動態代理物件

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(); } }