Getting and Setting fields

suggest change

Using the Reflection API, it is possible to read or change a field at runtime. For example, an API can select a field based on a factor such as the OS. Clearing the final bit in the Field object can also make some final fields writable. That does not undo inlining: a static final compile-time constant (String or primitive) may already have been copied into callers, so SomeClass.NAME can still print the old value. From Java 9, setAccessible on java.lang.reflect.Field fails unless that package is opened. getDeclaredField throws the checked exception NoSuchFieldException.

The example below uses Class#getDeclaredField(), not getField. getField only finds public fields, including inherited ones.

// Get the field in class SomeClass "NAME".
Field nameField = SomeClass.class.getDeclaredField("NAME");

// Get the field in class Field "modifiers". Note that it does not 
// need to be static
Field modifiersField = Field.class.getDeclaredField("modifiers");

// Allow access from anyone even if it's declared private
modifiersField.setAccessible(true);

// Get the modifiers on the "NAME" field as an int.
int existingModifiersOnNameField = nameField.getModifiers();

// Clear Modifier.FINAL (16) on the existing modifiers.
// See https://en.wikipedia.org/wiki/Bitwise_operations_in_C
// for the bitwise operators. getModifiers() is a masked view of the raw field.
int newModifiersOnNameField = existingModifiersOnNameField & ~Modifier.FINAL;

// Set the value of the modifiers field under an object for non-static fields
modifiersField.setInt(nameField, newModifiersOnNameField);

// Set it to be accessible. This overrides normal Java 
// private/protected/package/etc access control checks.
nameField.setAccessible(true);

 // Set the value of "NAME" here. Note the null argument. 
 // Pass null when modifying static fields, as there is no instance object
nameField.set(null, "Hacked by reflection...");

// Here I can directly access it. If needed, use reflection to get it. (Below)
System.out.println(SomeClass.NAME);

Getting fields is much easier. We can use Field#get() and its variants to get its value:

// Get the field in class SomeClass "NAME".
Field nameField = SomeClass.class.getDeclaredField("NAME");

// Set accessible for private fields
nameField.setAccessible(true);

// Pass null as there is no instance, remember?
String name = (String) nameField.get(null);

Do note this:

When using Class#getDeclaredField, use it to get a field in the class itself:

class HackMe extends Hacked {
    public String iAmDeclared;
}

class Hacked {
    public String someState;
}

HackMe.iAmDeclared is declared on HackMe. HackMe.someState is not: it is inherited from Hacked, so HackMe.class.getDeclaredField("someState") throws NoSuchFieldException. getField("someState") can still find it, because the field is public.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents