2009-06-28
■[Java]リフレクションでメソッドを呼び出してみる
第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); } }
トラックバック - http://d.hatena.ne.jp/d-kami/20090628/1246146263