通过Java中的反射访问私有继承的字段

我找到了一种通过获取继承成员并通过 class.getDeclaredFields(); 私有成员的方法,class.getFields() 但是我正在寻找私有继承字段。我怎样才能做到这一点?



慕码人8056858
浏览 720回答 3
3回答

MMTTMM

这应该演示如何解决它:import java.lang.reflect.Field;class Super {    private int i = 5;}public class B extends Super {    public static void main(String[] args) throws Exception {        B b = new B();        Field[] fs = b.getClass().getSuperclass().getDeclaredFields();        fs[0].setAccessible(true);        System.out.println(fs[0].get(b));    }}输出:5

杨魅力

这样就可以了:private List<Field> getInheritedPrivateFields(Class<?> type) {&nbsp; &nbsp; List<Field> result = new ArrayList<Field>();&nbsp; &nbsp; Class<?> i = type;&nbsp; &nbsp; while (i != null && i != Object.class) {&nbsp; &nbsp; &nbsp; &nbsp; Collections.addAll(result, i.getDeclaredFields());&nbsp; &nbsp; &nbsp; &nbsp; i = i.getSuperclass();&nbsp; &nbsp; }&nbsp; &nbsp; return result;}如果您使用EclEmma之类的代码覆盖工具,则必须当心:它们为每个类都添加了一个隐藏字段。在EclEmma的情况下,这些领域是明显的合成,而且可以过滤它们像这样:private List<Field> getInheritedPrivateFields(Class<?> type) {&nbsp; &nbsp; List<Field> result = new ArrayList<Field>();&nbsp; &nbsp; Class<?> i = type;&nbsp; &nbsp; while (i != null && i != Object.class) {&nbsp; &nbsp; &nbsp; &nbsp; for (Field field : i.getDeclaredFields()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!field.isSynthetic()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.add(field);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; i = i.getSuperclass();&nbsp; &nbsp; }&nbsp; &nbsp; return result;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java