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

(Continued from page 1)

If we execute ClassFieldTest, we obtain the following results:

pub field: this is public

pro field: this is protected

This will throw a NoSuchFieldException
java.lang.NoSuchFieldException: parentPub
	at java.lang.Class.getDeclaredField(
	at test.ClassFieldTest.main(

In summary, calling getDeclaredField() on a Class object can be used to obtain a Field object for a declared public, declared protected, or declared private field, and it throws an exception if an attempt is made to access an inherited field. Once a Field object is obtained, we can get and set the field value using the get() and set() methods on the Field object.

Page: < 1 2