记一次使用Xstream将XML转为java Bean报com.thoughtworks.xstream.mapper.CannotResolveClassException的坑

本文分享了一位开发者在使用XStream进行JavaBean转换时遇到的CannotResolveClassException异常问题及解决方案。通过调整XStream的类加载器,使其与目标JavaBean的类加载器保持一致,成功解决了跨工程调用时的兼容性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景:这段转换代码在工程中跑是没有问题的,但是一旦我将这个工程打成jar包,由其它工程调用的时候就会报com.thoughtworks.xstream.mapper.CannotResolveClassException异常。

解决办法:

查阅N多资料后,最终在CSDN中看到一位大神说可能是因为类加载器不同导致的,我且不去深究类加载器为何会不同,我做的只是验证,在我的代码中,这个要转换的Bean的加载器Xstream的加载器到底是不是一样的就行。我验证的代码如下:

XStream xstream = new XStream();
DtoVehiclLoginCsResult dtoVehiclLoginCS = new DtoVehiclLoginCsResult();
System.out.println("DtoVehiclLoginCsResult的加载器:" + dtoVehiclLoginCS.getClass().getClassLoader());
System.out.println("Xstream的加载器:" + xstream.getClassLoader());
            

 DtoVehiclLoginCsResult是我要转换的javaBean,最终结果是,javaBean使用的是java.net.URLClassLoader,而XStream使用的是其自定义的com.thoughtworks.xstream.core.util.CompositeClassLoader。

 

我将以上代码修改为如下,为XStream指定一个和JavaBean一样的ClassLoader:

XStream xstream = new XStream();
DtoVehiclLoginCsResult dtoVehiclLoginCS = new DtoVehiclLoginCsResult();
//为XStream指定ClassLoader
xstream.setClassLoader(dtoVehiclLoginCS.getClass().getClassLoader());
System.out.println("DtoVehiclLoginCsResult的加载器:" + dtoVehiclLoginCS.getClass().getClassLoader());
System.out.println("Xstream的加载器:" + xstream.getClassLoader());
            

测试一切正常了。问题不是很大的问题,但是困扰了我半下午,记录一下,加深印象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值