Skip to content

Instantly share code, notes, and snippets.

@tksmaru
Last active December 16, 2015 07:19
Show Gist options
  • Save tksmaru/5397956 to your computer and use it in GitHub Desktop.
Save tksmaru/5397956 to your computer and use it in GitHub Desktop.
リフレクションのおかげで寡黙な○野さんもお喋り好きになりました。
import java.lang.reflect.Field;
public class ReflectionTest {
public static void main(String[] args) throws Exception {
Mizuno mizuno = new Mizuno();
System.out.println("リフレクション前 : " + mizuno.talk()); // …
Class<? extends Mizuno> clazz = mizuno.getClass();
Field f = clazz.getDeclaredField("isSilent");
f.setAccessible(true);
f.set(mizuno, false); // ○野さんを魔改造
System.out.println("リフレクション後 : " + mizuno.talk()); // 僕はおしゃべりです
}
}
public class Mizuno {
// カプセル化されてて一見変更不可
private boolean isSilent = true;
public String talk() {
return isSilent ? "..." : "僕はおしゃべりです";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment