zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java反射异常:java.lang.NoSuchFieldException

2023-09-14 08:57:57 时间
p /p pre code_snippet_id= 1653182 snippet_file_name= blog_20160419_1_2018676 name= code >        今天用反射给对象赋值,有一个属性始终报错,主要错误信息如下:

java.lang.NoSuchFieldException: otherFeatures 

 at java.lang.Class.getDeclaredField(Unknown Source)

 at com.zxiaofan.MedicalAssistanObtainService.business.CrawlDataBusiness.setSpecialAttribute(CrawlDataBusiness.java:163)

 at com.zxiaofan.MedicalAssistanObtainService.business.CrawlDataBusiness.crawDrmedData(CrawlDataBusiness.java:106)

 at com.zxiaofan.MedicalAssistanObtainService.business.CrawlDataBusinessTest.test(CrawlDataBusinessTest.java:33)

 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)


网上说NoSuchFieldException错误是由于没有对应字段造成的,或者当属性为私有时获取Field用的方法不是getDeclaredField。

  Field field = bo.getClass().getDeclaredField(fieldName); // 正解

但是我的对象内确实是有otherFeatures属性的,而且用的是上述方法,查了好久,终于找到原因:

otherFeatures曾经从文本读取过,而文本里的otherFeatures多了空格,如果仔细查看,上面的异常也多了空格的!!!


So:NoSuchFieldException异常原因:①没有对应字段;②属性为私有时获取Field用的方法不是getDeclaredField。


死死往这两个方面去找原因吧。




Java服务CPU100%异常排查实践总结 写作目的 最近看牛客网发现了CPU 100% 怎么办这个问题,这个问题的重点是定位和解决,会用到Linux和java的的很多命令,所以写篇博客记录和总结一下。
zxiaofan 【zxiaofan.com】Life is all about choices!生命不息,学习不止。