Sobes.tech
Junior — Middle

Is it possible to change or read private variable values of a class through Reflection API?

sobes.tech AI

Answer from AI

Yes, through Reflection API in Java, you can access private fields of a class and modify or read their values. To do this, you need to call the setAccessible(true) method on the Field object to bypass access checks.

Example:

import java.lang.reflect.Field;

class Example {
    private String secret = "hidden";
}

Example obj = new Example();
Field field = Example.class.getDeclaredField("secret");
field.setAccessible(true); // allow access
String value = (String) field.get(obj); // read value
field.set(obj, "new value"); // change value
Is it possible to change or read private variable… - sobes.tech