logo пятница
09 января 2009г.

faking dynamic static dispatch

 вторник, 18 ноября 2008г. 09:20 (оригинал)  ivan_ghandhi ivan_ghandhi

Now details (under cut)

package experimental; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; public class A { String x; public A(String x) { this.x = x; } public String toString() { return "A(" + x + ")"; } public static A combine(A a1, A a2) { return new A(a1.x + " + " + a2.x); } public static A smartCombine(A a1, A a2) { Class class1 = a1.getClass(); try { Method method = class1.getMethod("combine", class1, a2.getClass()); return (A)method.invoke(null, a1, a2); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return combine(a1, a2); } }

And, similarly, class B:
package experimental; public class B extends A { public B(String x) { super(x); } public String toString() { return "B(" + x + ")"; } public static B combine(B b1, B b2) { return new B(b1.x + " * " + b2.x); } }

And the main test class:
package experimental; import static experimental.A.*; import static experimental.B.*; public class Polymorphism { public static void main(String[] args) { A a1 = new A("a1"); A a2 = new A("a2"); B b1 = new B("b1"); B b2 = new B("b2"); A x = b2; System.out.println(combine(a1, a2)); System.out.println(combine(b1, b2)); System.out.println(combine(a1, b2)); System.out.println(combine(b1, x)); System.out.println(smartCombine(b1, x)); } }

Well, yes, it prints this:
A(a1 + a2) B(b1 * b2) A(a1 + b2) A(b1 + b2) B(b1 * b2)

Комментарии Комментарии (0)   Теги ,
Google BookmarksDiggRedditdel.icio.usMa.gnoliaTechnoratiSlashdotYahoo My WebNews2.ruВаау!БобрДобр.ruMemori.ruМоёМесто.ruMister WongSEOmarksЗакладки I.UARUmarkzЯндекс.ЗакладкиBPoster.net




 Комментарии (0)

Комментарии RSS


 Добавить комментарий

 Имя
 Email
 Сайт


 Последние записи  ivan_ghandhi


Еще →