結(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
報異常:NoSuchFieldException
問題暴露在導(dǎo)出功能上熙卡,導(dǎo)出工具類芍锦,使用了getDeclaredField方法,如上圖所示裹虫。因為DTO類包含了caseId肿嘲,而導(dǎo)出對應(yīng)的bean也定義了caseId,類似的相同字段有多個筑公,于是我想優(yōu)化一下雳窟,讓導(dǎo)出bean繼承DTO,這樣可以刪除重復(fù)定義的字段匣屡。
所以導(dǎo)出bean這里是不能優(yōu)化的封救。