2023年12月8日发(作者:)
Java反射异常:FieldException
今天用反射给对象赋值,有一个属性始终报错,主要错误信息如下:
FieldException: otherFeatures
at laredField(Unknown Source)
at cialAttribute(:163)
at medData(:106)
at (:33)
at 0(Native Method)
at (Unknown Source)
网上说NoSuchFieldException错误是由于没有对应字段造成的,或者当属性为私有时获取Field用的方法不是getDeclaredField。
Field field = ss().getDeclaredField(fieldName); // 正解
但是我的对象内确实是有otherFeatures属性的,而且用的是上述方法,查了好久,终于找到原因:
otherFeatures曾经从文本读取过,而文本里的otherFeatures多了空格,如果仔细查看,上面的异常也多了空格的
So:NoSuchFieldException异常原因:①没有对应字段;②属性为私有时获取Field用的方法不是getDeclaredField。
死死往这两个方面去找原因吧。


发布评论