第127回 Ruby vs Java ダックタイピングとインタフェースで見る多態性を読んで、なんとなくリフレクションを使ってみたくなったので、リフレクションを使ったJavaのコードを書いた。C++のtemplateを使った人がいたので、俺はリフレクションを使うんだー!という勢いで書いた。
public class Human{ public void touch(Object obj) throws Exception{ obj.getClass().getMethod("say").invoke(obj); } }
class Duck{ public void say(){ System.out.println("ガーガー"); } }
class Dog{ public void say(){ System.out.println("ワンワン"); } }
public class Main{ public static void main(String[] args) throws Exception{ Human human = new Human(); Duck duck = new Duck(); Dog dog = new Dog(); human.touch(duck); human.touch(dog); } }
これで引数無しのsayを持つクラスのオブジェクトを渡せばsayを呼んでくれる