結(jié)論:只能獲取類本身的字段,對父類的字段無法獲取
// jdk中方法的注釋,對返回值的說明:
Returns:
the Field object for the specified field in this class
Throws:
NoSuchFieldException – if a field with the specified name is not found.
// 省略其他注釋
@CallerSensitive
public Field getDeclaredField(String name)
throws NoSuchFieldException, SecurityException {
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
Field field = searchFields(privateGetDeclaredFields(false), name);
if (field == null) {
throw new NoSuchFieldException(name);
}
return field;
}
下圖中caseId是父類中的private字段:

image.png
報(bào)異常:NoSuchFieldException
問題暴露在導(dǎo)出功能上,導(dǎo)出工具類,使用了getDeclaredField方法,如上圖所示。因?yàn)镈TO類包含了caseId,而導(dǎo)出對應(yīng)的bean也定義了caseId,類似的相同字段有多個,于是我想優(yōu)化一下,讓導(dǎo)出bean繼承DTO,這樣可以刪除重復(fù)定義的字段。
所以導(dǎo)出bean這里是不能優(yōu)化的。