import java.lang.reflect.*; public class ReflectionExample { public static void main(String[] args) { try { // same as Object fooObject = new Foo("Hello World", new Integer(37)); ... Class fooClass = Class.forName("Foo"); Class[] paramTypes = {Class.forName("java.lang.String"), Class.forName("java.lang.Integer")}; Constructor con = fooClass.getConstructor(paramTypes); Object[] paramValues = {"Hello World", new Integer(37)}; Object fooObject = con.newInstance(paramValues); Method[] methods = fooClass.getDeclaredMethods(); System.out.println("Foo has the methods:"); for (int i = 0; i < methods.length; i++) { System.out.println(" " + methods[i].getName()); } // same as System.out.println(fooObject.toString()); ... Class[] methodParamTypes = {}; Object[] methodParamValues = {}; System.out.println(fooClass.getMethod("toString", methodParamTypes).invoke(fooObject,methodParamValues)); // same as ((Foo) fooObject.setValue(3)); Class[] methodParamTypes2 = {Integer.TYPE}; // same as int.class Method setValueMethod = fooClass.getMethod("setValue", methodParamTypes2); Object[] methodParamValues2 = {new Integer(2)}; setValueMethod.invoke(fooObject,methodParamValues2); System.out.println(fooObject.toString()); } catch (Exception e) { e.printStackTrace(); } try { System.in.read(); // waits for the user to press "Enter" } catch (Exception e2) { e2.printStackTrace(); } } } class Foo { String message; Integer value; public Foo(String message, Integer value) { this.message = message; this.value = value; } public void setValue(int x) { value = new Integer(x); } public String toString() { return message + " " + value; } }