Junior — Middle
How can you change the internal state of a private variable of an object without using public methods like set?
sobes.tech AI
Answer from AI
To change the internal state of a private object variable without using public setters, you can apply reflection through the java.lang.reflect.Field class.
Example:
import java.lang.reflect.Field;
class MyClass {
private int secret = 42;
}
MyClass obj = new MyClass();
Field field = MyClass.class.getDeclaredField("secret");
field.setAccessible(true); // remove access restriction
field.setInt(obj, 100); // change the value
This approach allows you to modify private fields but breaks encapsulation and should be used with caution, for example, in tests or when working with legacy code.