リフレクション (2) - private
import java.lang.reflect.*; class Main { public static void main(String[] args) throws Exception { Constructor init = Hoge.class.getDeclaredConstructors()[0]; Field ans = Hoge.class.getDeclaredField("answer"); init.setAccessible(true); ans.setAccessible(true); System.out.println(ans.getInt(init.newInstance())); } } class Hoge { private int answer = 42; private Hoge() { } }
private メンバにもアクセスできる。
おまけ:
import java.lang.reflect.*; import java.util.*; class Main { public static void main(String[] args) throws Exception { Field f = Integer.class.getDeclaredField("value"); f.setAccessible(true); for (int i = -129; i <= 128; i++) f.setInt(Integer.valueOf(i), 0); List<Integer> list = new LinkedList<Integer>(); for (int i = -129; i <= 128; i++) list.add(i); System.out.println(list); } }
よく使う値はキャッシュされてたりするわけで。