1
2

More than 5 years have passed since last update.

Javaでprivateなフィールド&メソッドにアクセスする方法

Last updated at Posted at 2012-03-16
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);
    }
}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2