// File: TestClass.java (Module 8) // // Author: Rahul Simha // Created: October 7, 1998 // // Illustrates the Class class. import java.lang.reflect.*; class Obj_A { // Data. int n; double x; // Constructors. public Obj_A (int n, double x) { this.n = n; this.x = x; } public Obj_A () { this (0, 0); } // Methods. public static void print () { System.out.println ("Obj_A"); } public String toString () { return "Obj_A: n=" + n + ", x=" + x; } } public class TestClass { public static void call_toString (String obj_name) { try { // Get the Class instance first. Class c = Class.forName (obj_name); // Get a list of methods. Method[] method = c.getMethods(); // Go through and look for toString() for (int i=0; i < method.length; i++) { // Get name of i-th method. String name = method[i].getName(); // If it is toString ... if (name.equals ("toString")) { System.out.println (obj_name + " has a toString() method"); try { // Create an instance of the object on the fly. Object instance = c.newInstance (); // No parameters, so a size=0 array is passed. Object[] obj_array = new Object[0]; // Call the powerful invoke() method. // Note: toString returns a string. String output = (String) method[i].invoke (instance, obj_array); // Print out the string returned from toString() System.out.println ("String returned: " + output); } // Catch a whole bunch of exceptions. catch (InstantiationException e) { System.out.println (e); } catch (IllegalAccessException e) { System.out.println (e); } catch (InvocationTargetException e) { System.out.println (e); } } } } catch (ClassNotFoundException e) { System.out.println (e); } } public static void main (String[] argv) { // Simple test of Class: String s = "hello"; Class c = s.getClass (); System.out.println (c); // Use Obj_A instead. Obj_A a = new Obj_A (); c = a.getClass (); System.out.println (c); // Get constructors of Obj_A. Constructor[] ctor = c.getConstructors (); System.out.println ("Obj_A has " + ctor.length + " constructors"); // Get methods of Obj_A. Method[] method = c.getMethods(); System.out.println ("Obj_A has " + method.length + " methods: "); for (int i=0; i < method.length; i++) { String name = method[i].getName(); System.out.println (" " + name); } // Actually call a method (toString) in the object call_toString ("Obj_A"); } }