今天用反射给对象赋值,有一个属性始终报错,主要错误信息如下:
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)
Field field = bo.getClass().getDeclaredField(fieldName); // 正解
但是我的对象内确实是有otherFeatures属性的,而且用的是上述方法,查了好久,终于找到原因:
otherFeatures曾经从文本读取过,而文本里的otherFeatures多了空格,如果仔细查看,上面的异常也多了空格的!!!
So:NoSuchFieldException异常原因:①没有对应字段;②属性为私有时获取Field用的方法不是getDeclaredField。
死死往这两个方面去找原因吧。