通过Java中的反射访问私有继承的字段 [英] Access to private inherited fields via reflection in Java

查看:281
本文介绍了通过Java中的反射访问私有继承的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found a way to get inherited members via class.getDeclaredFields(); and acces to private members via class.getFields() But i'm looking for private inherited fields. How can i achieve this?

推荐答案

实际上我使用的是复杂类型层次结构,因此您的解决方案并不完整。
我需要进行递归调用以获取所有私有继承的字段。
这是我的解决方案

In fact i use a complex type hierachy so you solution is not complete. I need to make a recursive call to get all the private inherited fields. Here is my solution

 /**
 * Return the set of fields declared at all level of class hierachy
 */
public Vector<Field> getAllFields(Class clazz) {
    return getAllFieldsRec(clazz, new Vector<Field>());
}

private Vector<Field> getAllFieldsRec(Class clazz, Vector<Field> vector) {
    Class superClazz = clazz.getSuperclass();
    if(superClazz != null){
        getAllFieldsRec(superClazz, vector);
    }
    vector.addAll(toVector(clazz.getDeclaredFields()));
    return vector;
}

这篇关于通过Java中的反射访问私有继承的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆