无法从基类访问字段值

时间:2013-11-27 08:09:28

标签: java class reflection

我在Java中有一个名为A的基类和一个派生类名B. 我想从A(基类)访问B的私有或公共变量的值 我可以使用以下代码读取变量名称但不能读取变量值:

protected void loadValues()
    {
        Field[] fields = this.getClass().getDeclaredFields();
        for(Field field:fields){
            try {
                xLog.info(field.getName()+"-"+field.get(this).toString());
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

错误是: 不允许访问字段。

我可以轻松地在C#中完成。我怎么能在java中这样做? 这是我在C#中的方式:

   private void loadValues()
    {
        foreach (var item in GetType().GetFields())
        {
            Type type = item.FieldType;
            object value = item.GetValue(this);
            fields.Add(new Tuple<string, Type, object>(item.Name, type, value));
        }
    }

2 个答案:

答案 0 :(得分:5)

在阅读该字段之前执行field.setAccessible(true);

中实现这样的循环依赖之前,真的真的再想一想。这样反转继承是否真的是你问题的最佳解决方案?

反射是一种强大的工具,但通常会有一种相当不干净的解决方案的味道。

答案 1 :(得分:3)

在访问该字段之前,您必须使用field.setAccessible(true);

示例:

public static class A {
    public void test() throws Exception {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            System.out.println(field.getName() + "-" + field.get(this).toString());
        }
    }
}

public static class B extends A {
    private String foo = "bar";
    public B() throws Exception {
        super();
        test();
    }
}

public static void main(String[] args) throws Exception {
    new B();
}

打印:

foo-bar