Last active
December 16, 2015 07:19
-
-
Save tksmaru/5397956 to your computer and use it in GitHub Desktop.
リフレクションのおかげで寡黙な○野さんもお喋り好きになりました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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