获取动态代理对象

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

猜你喜欢

转载自www.cnblogs.com/Su-feng-address/p/9942518.html