2022-04-11 jdk中getDeclaredField返回什么字段

结论:只能获取类本身的字段,对父类的字段无法获取

// 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
问题暴露在导出功能上,导出工具类,使用了getDeclaredField方法,如上图所示。因为DTO类包含了caseId,而导出对应的bean也定义了caseId,类似的相同字段有多个,于是我想优化一下,让导出bean继承DTO,这样可以删除重复定义的字段。
所以导出bean这里是不能优化的。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容