fork download
  1.  
  2. import java.util.ArrayDeque;
  3. import java.util.Iterator;
  4. import java.lang.reflect.Method;
  5.  
  6. class HelloWorld
  7. {
  8. public static void main(String[] args) throws Exception
  9. {
  10. Delegate d = new Delegate();
  11. d.add(null, HelloWorld.class, "foo");
  12. d.add(null, HelloWorld.class, "bar");
  13. d.invoke();
  14. }
  15.  
  16. public static void foo()
  17. {
  18. System.out.println("foo");
  19. }
  20.  
  21. public static void bar()
  22. {
  23. System.out.println("bar");
  24. }
  25.  
  26. static class Delegate
  27. {
  28. ArrayDeque<Pair> methods = new ArrayDeque<Pair>();
  29. Class<?>[] parameterTypes;
  30.  
  31. public Delegate(Class<?>... parameterTypes)
  32. {
  33. this.parameterTypes = parameterTypes;
  34. }
  35.  
  36. public void add(Object o, Class c, String n) throws Exception
  37. {
  38. Method m = c.getDeclaredMethod(n, parameterTypes);
  39. methods.add(new Pair(o, m));
  40. }
  41.  
  42. public void remove(Object o, Class c, String n) throws Exception
  43. {
  44. Method m = c.getDeclaredMethod(n, parameterTypes);
  45. methods.remove(new Pair(o, m));
  46. }
  47.  
  48. public Object invoke(Object... args) throws Exception
  49. {
  50. Object r = null;
  51. for (Iterator<Pair> i = methods.iterator(); i.hasNext(); )
  52. {
  53. Pair p = i.next();
  54. if (args.length == 0)
  55. {
  56. r = p.m.invoke(p.c);
  57. }
  58. else
  59. {
  60. r = p.m.invoke(p.c, args);
  61. }
  62. }
  63. return r;
  64. }
  65.  
  66. class Pair
  67. {
  68. public final Object c;
  69. public final Method m;
  70. Pair(Object c, Method m)
  71. {
  72. this.c = c;
  73. this.m = m;
  74. }
  75. public int hashCode()
  76. {
  77. int h = 0;
  78. if (c != null) h ^= c.hashCode();
  79. if (m != null) h ^= m.hashCode();
  80. return h;
  81. }
  82. public boolean equals(Object obj)
  83. {
  84. if (obj == null) return false; if (this == obj) return true;
  85. if (!(obj instanceof Pair)) return false;
  86. Pair p = (Pair)obj;
  87. return (this.c == p.c) && this.m.equals(p.m);
  88. }
  89. }
  90. }
  91. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
foo
bar