Invoke

This application invokes two of the methods in the Mystery class

import java.lang.reflect.*;

public class ReflectInvoke  {


  public ReflectInvoke ()  {
    super ();
  }  // end ReflectInvoke constructor

  public static void main ( String [ ] args )  {

    try  {

        Class theClass = Class.forName("Mystery");
        String s = theClass.getName();
        System.out.println("Name of class: " + s);
        System.out.println();

        System.out.println("Methods declared in class: " );
        Method[] theMethods = theClass.getDeclaredMethods();
        for (int i = 0; i < theMethods.length; i++) {
            String methodName = theMethods[i].getName();
            System.out.println(i+" Method Name: " + methodName);
            String returnString = theMethods[i].getReturnType().getName();
            System.out.println("   Return Type: " + returnString);
            Class[] parmTypes = theMethods[i].getParameterTypes();
            System.out.print("   Parameter Types:");
            for (int j = 0; j < parmTypes.length; j++) {
                String parmString = parmTypes[j].getName();
                System.out.print(" " + parmString);
            }  // end for: j
            System.out.println();
            System.out.println();
        }  // end for: i

        Object theObject = theClass.newInstance();
        Class thisClass = theObject.getClass();
        Method thisMethod = thisClass.getMethod("getMessage",null);

        String result1 = (String) thisMethod.invoke( theObject, null);
        System.out.println("getMessage returns: " + result1 );
        System.out.println();

        Method thatMethod = thisClass.getMethod("getNumber",null);
        Integer result2 = (Integer) thatMethod.invoke( theObject, null);
        System.out.println("getNumber returns: " + result2 );


    } // end try

    catch ( ClassNotFoundException e ) {
        System.out.println ( "Class not found: " + e );
    }
    catch (InstantiationException e) {
        System.out.println ( "Instantion error: " + e );
    }
    catch (IllegalAccessException e) {
        System.out.println ( "Illegal access: " + e );
    }
    catch (NoSuchMethodException e) {
          System.out.println( "No such method: " + e);
    }
    catch (InvocationTargetException e) {
          System.out.println( "Target exception: " + e);
    }


  }  // end main


}  // end ReflectInvoke