Set private field value with reflection

Using FieldUtils from the Apache Commons Lang 3:

FieldUtils.writeField(childInstance, "a_field", "Hello", true);

The true forces it to set, even if the field is private.


To access a private field you need to set Field::setAccessible to true. You can pull the field off the super class. This code works:

Class<?> clazz = Child.class;
Object cc = clazz.newInstance();

Field f1 = cc.getClass().getSuperclass().getDeclaredField("a_field");
f1.setAccessible(true);
f1.set(cc, "reflecting on life");
String str1 = (String) f1.get(cc);
System.out.println("field: " + str1);