- Getting and Setting Field Values
- Class Field
- Field Summary
- Fields declared in interface java.lang.reflect.Member
- Method Summary
- Methods declared in class java.lang.reflect.AccessibleObject
- Methods declared in class java.lang.Object
- Method Details
- setAccessible
- getDeclaringClass
- getName
- getModifiers
- accessFlags
- isEnumConstant
- isSynthetic
- getType
- getGenericType
- equals
- hashCode
- toString
- toGenericString
- get
- getBoolean
Getting and Setting Field Values
Given an instance of a class, it is possible to use reflection to set the values of fields in that class. This is typically done only in special circumstances when setting the values in the usual way is not possible. Because such access usually violates the design intentions of the class, it should be used with the utmost discretion.
The Book class illustrates how to set the values for long, array, and enum field types. Methods for getting and setting other primitive types are described in Field .
import java.lang.reflect.Field; import java.util.Arrays; import static java.lang.System.out; enum Tweedle < DEE, DUM >public class Book < public long chapters = 0; public String[] characters = < "Alice", "White Rabbit" >; public Tweedle twin = Tweedle.DEE; public static void main(String. args) < Book book = new Book(); String fmt = "%6S: %-12s = %s%n"; try < Classc = book.getClass(); Field chap = c.getDeclaredField("chapters"); out.format(fmt, "before", "chapters", book.chapters); chap.setLong(book, 12); out.format(fmt, "after", "chapters", chap.getLong(book)); Field chars = c.getDeclaredField("characters"); out.format(fmt, "before", "characters", Arrays.asList(book.characters)); String[] newChars = < "Queen", "King" >; chars.set(book, newChars); out.format(fmt, "after", "characters", Arrays.asList(book.characters)); Field t = c.getDeclaredField("twin"); out.format(fmt, "before", "twin", book.twin); t.set(book, Tweedle.DUM); out.format(fmt, "after", "twin", t.get(book)); // production code should handle these exceptions more gracefully > catch (NoSuchFieldException x) < x.printStackTrace(); >catch (IllegalAccessException x) < x.printStackTrace(); >> >
This is the corresponding output:
$ java Book BEFORE: chapters = 0 AFTER: chapters = 12 BEFORE: characters = [Alice, White Rabbit] AFTER: characters = [Queen, King] BEFORE: twin = DEE AFTER: twin = DUM
Note: Setting a field’s value via reflection has a certain amount of performance overhead because various operations must occur such as validating access permissions. From the runtime’s point of view, the effects are the same, and the operation is as atomic as if the value was changed in the class code directly.
Use of reflection can cause some runtime optimizations to be lost. For example, the following code is highly likely be optimized by a Java virtual machine:
Equivalent code using Field.set*() may not.
Class Field
A Field provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field.
A Field permits widening conversions to occur during a get or set access operation, but throws an IllegalArgumentException if a narrowing conversion would occur.
Field Summary
Fields declared in interface java.lang.reflect.Member
Method Summary
Returns an AnnotatedType object that represents the use of a type to specify the declared type of the field represented by this Field.
Returns this element’s annotation for the specified type if such an annotation is present, else null.
Gets the value of a static or instance field of type char or of another primitive type convertible to type char via a widening conversion.
Returns the Class object representing the class or interface that declares the field represented by this Field object.
Gets the value of a static or instance field of type double or of another primitive type convertible to type double via a widening conversion.
Gets the value of a static or instance field of type float or of another primitive type convertible to type float via a widening conversion.
Returns a Type object that represents the declared type for the field represented by this Field object.
Gets the value of a static or instance field of type int or of another primitive type convertible to type int via a widening conversion.
Gets the value of a static or instance field of type long or of another primitive type convertible to type long via a widening conversion.
Gets the value of a static or instance field of type short or of another primitive type convertible to type short via a widening conversion.
Returns a Class object that identifies the declared type for the field represented by this Field object.
Sets the field represented by this Field object on the specified object argument to the specified new value.
Methods declared in class java.lang.reflect.AccessibleObject
Methods declared in class java.lang.Object
Method Details
setAccessible
- C and D are in the same module.
- The member is public and D is public in a package that the module containing D exports to at least the module containing C .
- The member is protected static , D is public in a package that the module containing D exports to at least the module containing C , and C is a subclass of D .
- D is in a package that the module containing D opens to at least the module containing C . All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.
- The member is public and D is public in a package that the module containing D exports unconditionally.
This method cannot be used to enable access to private members, members with default (package) access, protected instance members, or protected constructors when the declaring class is in a different module to the caller and the package containing the declaring class is not open to the caller’s module.
- static final fields declared in any class or interface
- final fields declared in a hidden class
- final fields declared in a record
The accessible flag when true suppresses Java language access control checks to only enable read access to these non-modifiable final fields.
If there is a security manager, its checkPermission method is first called with a ReflectPermission(«suppressAccessChecks») permission.
getDeclaringClass
Returns the Class object representing the class or interface that declares the field represented by this Field object.
getName
getModifiers
Returns the Java language modifiers for the field represented by this Field object, as an integer. The Modifier class should be used to decode the modifiers.
accessFlags
isEnumConstant
isSynthetic
getType
Returns a Class object that identifies the declared type for the field represented by this Field object.
getGenericType
Returns a Type object that represents the declared type for the field represented by this Field object. If the declared type of the field is a parameterized type, the Type object returned must accurately reflect the actual type arguments used in the source code. If the type of the underlying field is a type variable or a parameterized type, it is created. Otherwise, it is resolved.
equals
Compares this Field against the specified object. Returns true if the objects are the same. Two Field objects are the same if they were declared by the same class and have the same name and type.
hashCode
Returns a hashcode for this Field . This is computed as the exclusive-or of the hashcodes for the underlying field’s declaring class name and its name.
toString
Returns a string describing this Field . The format is the access modifiers for the field, if any, followed by the field type, followed by a space, followed by the fully-qualified name of the class declaring the field, followed by a period, followed by the name of the field. For example:
public static final int java.lang.Thread.MIN_PRIORITY private int java.io.FileDescriptor.fd
The modifiers are placed in canonical order as specified by «The Java Language Specification». This is public , protected or private first, and then other modifiers in the following order: static , final , transient , volatile .
toGenericString
Returns a string describing this Field , including its generic type. The format is the access modifiers for the field, if any, followed by the generic field type, followed by a space, followed by the fully-qualified name of the class declaring the field, followed by a period, followed by the name of the field. The modifiers are placed in canonical order as specified by «The Java Language Specification». This is public , protected or private first, and then other modifiers in the following order: static , final , transient , volatile .
get
Returns the value of the field represented by this Field , on the specified object. The value is automatically wrapped in an object if it has a primitive type. The underlying field’s value is obtained as follows: If the underlying field is a static field, the obj argument is ignored; it may be null. Otherwise, the underlying field is an instance field. If the specified obj argument is null, the method throws a NullPointerException . If the specified object is not an instance of the class or interface declaring the underlying field, the method throws an IllegalArgumentException . If this Field object is enforcing Java language access control, and the underlying field is inaccessible, the method throws an IllegalAccessException . If the underlying field is static, the class that declared the field is initialized if it has not already been initialized. Otherwise, the value is retrieved from the underlying instance or static field. If the field has a primitive type, the value is wrapped in an object before being returned, otherwise it is returned as is. If the field is hidden in the type of obj , the field’s value is obtained according to the preceding rules.