java中CGLIB动态代理怎么实现

PHPz
PHPz转载
2023-05-11 10:49:06851浏览

1、说明

CGLIB是一个功能强大,高性能的代码生成包。它为没有实现接口的类提供代理,为JDK的动态代理提供了很好的补充。

CGLIB是第三方提供的包,所以需要引入jar包的坐标:

2、实例

public class HelloWorld {
    public static void main(String[] args) {
        // 创建代理工厂对象
        ProxyFactory factory = new ProxyFactory();
        
        // 获取代理对象
        TrainStation proxyObject = factory.getProxyObject();
        
        proxyObject.sell();
    }
}
 
// 火车站,火车站具有卖票功能
class TrainStation {
    public void sell() {
        System.out.println("火车站卖票");
    }
}
 
// 代理工厂
public class ProxyFactory implements MethodInterceptor {
    private TrainStation target = new TrainStation();
 
    public TrainStation getProxyObject() {
        // 创建Enhancer对象,类似于JDK动态代理的Proxy类,下一步就是设置几个参数
        Enhancer enhancer = new Enhancer();
        
        // 设置父类的字节码对象
        enhancer.setSuperclass(target.getClass());
        
        // 设置回调函数
        enhancer.setCallback(this);
        
        // 创建代理对象
        TrainStation obj = (TrainStation) enhancer.create();
        
        return obj;
    }
    
    public TrainStation intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        /**
         * intercept方法参数说明:
         *  o:代理对象
         *  method:真实对象中的方法的Method实例
         *  args:实际参数
         *  methodProxy:代理对象中的方法的method实例
         */
        
        System.out.println("代理点收取一些服务费用(CGLIB动态代理)");
        
        TrainStation result = (TrainStation) methodProxy.invokeSuper(o, args);
        
        return result;
    }
}

以上就是java中CGLIB动态代理怎么实现的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除
PHP培训优惠套餐