How can you access a protected
field in a base class's base class that is hidden by a field in a base class?
An example:
package foo;
public class Foo {
protected int x;
int getFooX() { return x; }
}
package bar;
public class Bar extends foo.Foo {
protected int x;
// Can access foo.Foo#x through super.x
}
The Foo
class's x
field is shadowed by Bar
's field of the same name, but can be accessed by reflection:
package baz;
public class Baz extends bar.Bar {
{
// Want getFooX() to return 2
// ((foo.Foo) this).x = 2; // Fails due to access error; Makes sense
// super.x = 2; // Changes bar.Bar#x
// super.super.x = 2; // Syntax error
// foo.Foo.this.x = 2; // Syntax error
try {
Field Foo_x = foo.Foo.class.getDeclaredField("x");
Foo_x.setAccessible(true);
Foo_x.setInt(this, 2);
} catch (ReflectiveOperationException e) { e.printStackTrace(); }
// Doesn't compile error if field changes name
}
}
Is there a way to do this without reflection, and without making changes to the superclasses?