Set private field value
import java.lang.reflect.Field;
public class FieldTroubleToo {
public final boolean b = true;
public static void main(String... args) {
FieldTroubleToo ft = new FieldTroubleToo();
try {
Class<?> c = ft.getClass();
Field f = c.getDeclaredField("b");
// f.setAccessible(true); // solution
f.setBoolean(ft, Boolean.FALSE); // IllegalAccessException
// production code should handle these exceptions more gracefully
} catch (NoSuchFieldException x) {
x.printStackTrace();
} catch (IllegalArgumentException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
}
}
}
Home
Java Book
Runnable examples
Java Book
Runnable examples
Reflection Field:
- Get all fields
- Get all Declared Fields
- Get annotations for a Field
- Get "public static final" field
- Get specific fields
- Get Field value by field name
- Get fields for super class
- Get Inherited Methods and fields
- Get Type of the field or return type of a method.
- Field modifiers: isSynthetic, isEnumConstant
- Set field value
- Set null to a field value
- Set private field value