How do I get and set a field using reflection?
Author: Deron Eriksson
Description: This Java tutorial describes how to get and set a field using reflection.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.4
(Continued from page 1)
If we execute ClassFieldTest, we obtain the following results:
pub field: reflecting on life parentPub field: again This will throw a NoSuchFieldException java.lang.NoSuchFieldException: pro at java.lang.Class.getField(Class.java:1507) at test.ClassFieldTest.main(ClassFieldTest.java:23)
As you can see, we were able to use the getField() method to get Field objects representing public fields, and we could then use the Field objects to set and get the field values. We also saw how trying to call getField() on a protected or private field results in a NoSuchFieldException.