With a class, Test
, as such:
public class Test {
public int field1;
}
And a subclass, SubTest
, as such:
//This class extends Test
public class SubTest extends Test {
public SubTest(int value) {
field1 = value;//field1 is public, so we can access it from subclass.
}
}
We can do the following with a Field
object:
public static void main(String[] args)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
SubTest t0 = new SubTest(-10), t1 = new SubTest(0), t2 = new SubTest(10);
Field f = SubTest.class.getField("field1");
System.out.println(f.get(t0));
System.out.println(f.get(t1));
System.out.println(f.get(t2));
}
Prints:
-10
0
10
Explanation: The Field
class in Java can be obtained from a Class
object (not an instance of a class) and can be used to manipulate/read the actual field that it represents on objects. In this example we got the Field
class that represents field1
and then we used that to get the value of the actual field from each SubTest
we created.
Please note the exceptions thrown by the main method. Java reflection can sometimes throw many checked exceptions.
If the field in your superclass (Test
) is private
, you will need to get the superclass of your class (meaning, the superclass of SubTest
) then get the declared fields from that. See this link as Zabuza pointed out for more information.