Java反射异常:java.lang.NoSuchFieldException

        今天用反射给对象赋值,有一个属性始终报错,主要错误信息如下:

[html] view plain copy
 
  1. java.lang.NoSuchFieldException: otherFeatures   
  2.     at java.lang.Class.getDeclaredField(Unknown Source)  
  3.     at com.zxiaofan.MedicalAssistanObtainService.business.CrawlDataBusiness.setSpecialAttribute(CrawlDataBusiness.java:163)  
  4.     at com.zxiaofan.MedicalAssistanObtainService.business.CrawlDataBusiness.crawDrmedData(CrawlDataBusiness.java:106)  
  5.     at com.zxiaofan.MedicalAssistanObtainService.business.CrawlDataBusinessTest.test(CrawlDataBusinessTest.java:33)  
  6.     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  
  7.     at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)  
网上说NoSuchFieldException错误是由于没有对应字段造成的,或者当属性为私有时获取Field用的方法不是getDeclaredField。

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

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

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

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

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

[javascript] view plain copy
 
  1. 欢迎个人转载,但须在文章页面明显位置给出原文连接;  
  2. 未经作者同意必须保留此段声明、不得随意修改原文、不得用于商业用途,否则保留追究法律责任的权利。  
  3.   
  4. 【 CSDN 】:csdn.zxiaofan.com  
  5. 【GitHub】:github.zxiaofan.com  
  6.   
  7. 如有任何问题,欢迎留言。祝君好运!  
  8. Life is all about choices!   
  9. 将来的你一定会感激现在拼命的自己!  
原文地址:https://www.cnblogs.com/KingIceMou/p/8072879.html