Junior — Middle
How can you access private fields of an object through reflection?
sobes.tech AI
Answer from AI
In Java, reflection can be used to access private fields of an object by changing their accessibility with the setAccessible(true) method. This allows reading and modifying the values of such fields.
Example:
import java.lang.reflect.Field;
public class Example {
private String secret = "hidden";
public static void main(String[] args) throws Exception {
Example obj = new Example();
Field field = Example.class.getDeclaredField("secret");
field.setAccessible(true); // remove access restriction
// Read the value of the private field
String value = (String) field.get(obj);
System.out.println("Secret value: " + value);
// Change the value of the private field
field.set(obj, "revealed");
System.out.println("New secret value: " + field.get(obj));
}
}
It is important to remember that using setAccessible(true) can break encapsulation and should be used with caution.