The Java Program: Invoke.java

  1 import java.lang.reflect.Method;
  2 import java.lang.reflect.InvocationTargetException;
  3 import java.awt.Component;
  4 import java.awt.Button;
  5 
  6 class Invoke {
  7 
  8    public static void main(String[] args) {
  9       C c = new C();
 10 
 11       // Demonstrate that if return type is primitive, it is wrapped
 12       // with an Object wrapper.
 13       invoke(c, "m1", new Class[] {}, new Object[] {});
 14 
 15       // Demonstrate that if parameter is primitive, must wrap with
 16       // Object wrapper.
 17       invoke (c, "m2", new Class[] {double.class}, 
 18          new Object[] {new Double(0)});
 19 
 20       // Demonstrate that an int value can be widened to a double.
 21       // Also demonstrate how to handle m2's exception.
 22       invoke (c, "m2", new Class[] {double.class}, 
 23          new Object[] {new Integer(100)});
 24 
 25       // Demonstrate that Button can be widened to Component.
 26       invoke (c, "m3", new Class[] {Component.class}, 
 27          new Object[] {new Button("OK")});
 28 
 29       // Demonstrate that even though the method object refers to C.m1(),
 30       // D.m1() will be called.
 31       D d = new D();
 32       invoke(d, "m1", new Class[] {}, new Object[] {});
 33    }
 34 /*
 35 m1() -> java.lang.Double: 3.14
 36 m2() -> void: null
 37 m2() -> java.lang.IllegalArgumentException
 38         at C.m2(Compiled Code)
 39         at java.lang.reflect.Method.invoke(Native Method)
 40         at Invoke.invoke(Compiled Code)
 41         at Invoke.main(Compiled Code)
 42 m3() -> void: null
 43 m1() -> java.lang.Double: 6.28
 44 */
 45 
 46    public static void invoke (
 47       Object o, String name, Class[] params, Object[] args) {
 48       try {
 49          Method m = C.class.getDeclaredMethod(name, params);
 50          System.out.print (name + "() -> ");
 51 
 52          Object r = m.invoke(o, args);
 53     
 54          if (r != null) {
 55             System.out.println (r.getClass().getName()+": "+r);
 56          } else {
 57             System.out.println (m.getReturnType().getName()+": "+r);
 58          }
 59       } catch (NoSuchMethodException e) {
 60          e.printStackTrace();
 61       } catch (IllegalAccessException e) {
 62          e.printStackTrace();
 63       } catch (InvocationTargetException e) {
 64          e.getTargetException().printStackTrace();
 65       }
 66    }
 67 }
 68 
 69 class C {
 70    double m1() { return 3.14; }
 71 
 72    void m2(double d) throws IllegalArgumentException {
 73       if (d > 50) {
 74          throw new IllegalArgumentException();
 75       }
 76    }
 77 
 78    void m2(int i) {
 79       System.out.println("*** NOT REACHED ***");
 80    }
 81 
 82    void m3(Component c) { }
 83 }
 84 
 85 class D extends C {
 86     double m1() { return 2*super.m1(); }
 87 }