ehsan shirzadi
ehsan shirzadi

Reputation: 4859

Can not access filed values from base class

I have a base class in Java named A And a derived class name B. I want to access the values of the private or public variables of B from A(base class).
I can read the variable names but not variable value with this code:

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();
            }
        }

The error is: access to field not allowed.

I can do it in C# easily. how can I do this in java? Here is the way I'm doing it in 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));
        }
    }

Upvotes: 2

Views: 193

Answers (2)

Matthias
Matthias

Reputation: 3592

Do field.setAccessible(true); before reading from that field.

And also really really think again before implementing a cyclic dependency like this in Java. Is it really the best solution to your problem to invert inheritance like this?

Reflection is a powerful tool, but usually has the smell of a rather unclean solution.

Upvotes: 5

sp00m
sp00m

Reputation: 48837

You have to use field.setAccessible(true); before accessing the field.

Example:

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();
}

Prints:

foo-bar

Upvotes: 3

Related Questions