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
If you have an object in JavaSW, you can get its Class object by calling getClass() on the object. You can call getField() on the Class object to get a Field object for a public field of the class, including inherited public fields. You can set the value of the field by calling the set() method on the Field object, where the first parameter is the object that has the field value that you'd like to set, and the second parameter is the value of that field. There are other 'set' methods for primitive (non-object) field types. To get the value of a public field, you can call the get() method of the Field object, with the object featuring the field value that you'd like to get as the first parameter. This is demonstrated in the ClassFieldTest object, which sets and gets a field in FieldTest and also sets and gets a field that FieldTest inherits from ParentFieldTest. It also demonstrates attempting to get a protected field using getField(), which throws an error since getField() can't be used for protected or private fields. ClassFieldTest.javapackage test; import java.lang.reflect.Field; public class ClassFieldTest { public static void main(String args[]) throws Exception { FieldTest ft = new FieldTest(); Class ftClass = ft.getClass(); Field f1 = ftClass.getField("pub"); f1.set(ft, "reflecting on life"); String str1 = (String) f1.get(ft); System.out.println("pub field: " + str1); Field f2 = ftClass.getField("parentPub"); f2.set(ft, "again"); String str2 = (String) f2.get(ft); System.out.println("\nparentPub field: " + str2); try { System.out.println("\nThis will throw a NoSuchFieldException"); Field f3 = ftClass.getField("pro"); } catch (Exception e) { e.printStackTrace(); } } } ParentFieldTest is shown here. ParentFieldTest.javapackage test; public class ParentFieldTest { private String parentPri; protected String parentPro; public String parentPub; public ParentFieldTest() { } } FieldTest is shown here. FieldTest.javapackage test; public class FieldTest extends ParentFieldTest { private String pri; protected String pro; public String pub; public FieldTest() { } public FieldTest(String pri, String pro, String pub) { this.pri = pri; this.pro = pro; this.pub = pub; } } (Continued on page 2) Related Tutorials:
|