java中CGLIB动态代理的介绍

java中CGLIB动态代理的介绍,第1张

java中CGLIB动态代理的介绍

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 {
        
        
        System.out.println("代理点收取一些服务费用(CGLIB动态代理)");
        
        TrainStation result = (TrainStation) methodProxy.invokeSuper(o, args);
        
        return result;
    }
}

以上就是java中CGLIB动态代理的介绍,希望能对大家有所帮助。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/3017361.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-28
下一篇 2022-09-28

发表评论

登录后才能评论

评论列表(0条)

保存