How do I get and set a declared field using reflection?
Author: Deron Eriksson
Description: This Java tutorial describes how to get and set a declared field using reflection.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.4


Page:    1 2 >

In another tutorial, we saw how we can call getField() on a Class object to obtain a Field object, and how we can call set() and get() on this Field object with the particular object on which the field exists passed as the first parameter to set() and get(). The getField() method can return any public field of an object, including inherited fields, and it throws an exception if you try to call getField() on a protected or private field. So, how can you get a protected or private field so that you can get or set it?

A Class object has a getDeclaredField() method that allows you to obtain a public, protected, or private declared field of an object, but not an inherited field. If you try to get an inherited field using getDeclaredField(), an exception will be thrown. Once you obtain a Field object from getDeclaredField(), you can call get() and set() on it, as shown in ClassFieldTest.

ClassFieldTest demonstrates calling getDeclaredField() to get a public declared field and a protected declared field. It calls set() and get() methods on both of the Field objects that are obtained. It also demonstrates how a NoSuchFieldException is thrown when an attempt is made to call getDeclaredField() to get an inherited public field.

ClassFieldTest.java

package 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.getDeclaredField("pub");
		f1.set(ft, "this is public");
		String str1 = (String) f1.get(ft);
		System.out.println("pub field: " + str1);

		Field f2 = ftClass.getDeclaredField("pro");
		f2.set(ft, "this is protected");
		String str2 = (String) f2.get(ft);
		System.out.println("\npro field: " + str2);

		try {
			System.out.println("\nThis will throw a NoSuchFieldException");
			Field f3 = ftClass.getDeclaredField("parentPub");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

ParentFieldTest is shown here.

ParentFieldTest.java

package test;

public class ParentFieldTest {

	private String parentPri;
	protected String parentPro;
	public String parentPub;

	public ParentFieldTest() {
	}

}

FieldTest is shown here.

FieldTest.java

package 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)

Page:    1 2 >