今天用反射给对象赋值,有一个属性始终报错,主要错误信息如下:
网上说nosuchfieldexception错误是由于没有对应字段造成的,或者当属性为私有时获取field用的方法不是getdeclaredfield。
field field = bo.getclass().getdeclaredfield(fieldname); // 正解
但是我的对象内确实是有otherfeatures属性的,而且用的是上述方法,查了好久,终于找到原因:
otherfeatures曾经从文本读取过,而文本里的otherfeatures多了空格,如果仔细查看,上面的异常也多了空格的!!!
so:nosuchfieldexception异常原因:①没有对应字段;②属性为私有时获取field用的方法不是getdeclaredfield。
死死往这两个方面去找原因吧。