美文网首页
2022-04-11 jdk中getDeclaredField

2022-04-11 jdk中getDeclaredField

作者: 归去来ming | 来源:发表于2022-04-11 15:44 被阅读0次

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

// 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这里是不能优化的。

相关文章

网友评论

      本文标题:2022-04-11 jdk中getDeclaredField

      本文链接:https://www.haomeiwen.com/subject/hagisrtx.html