Main.java
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
MyClass obj = new MyClass("abc");
// Compile error
// obj.print();
Method method = obj.getClass().getDeclaredMethod("print", new Class[] {});
method.setAccessible(true);
method.invoke(obj, new Object[] {});
Field nameField = obj.getClass().getDeclaredField("str");
nameField.setAccessible(true);
nameField.set(obj, "def");
method.invoke(obj, new Object[] {});
}
}
MyClass.java
public class MyClass {
private final String str;
public MyClass(String str) {
this.str = str;
}
private void print() {
System.out.println(str);
}
}