Java reflection example code 

Joined:
03/07/2011
Posts:
57

May 24, 2011 14:52:53    Last update: May 26, 2011 19:52:12
import java.lang.reflect.Method;

public class ReflectionTest {
    public static void main(String[] args) throws Exception {
	Class<?> c = Class.forName("ReflectionTest");
	Object o = c.newInstance();

	// instance method
	Method getValue = c.getMethod("getValue");
	String value = (String) getValue.invoke(o);
	System.out.println("Results from getValue: " + value);

	// static method
	Method getStaticValue = c.getMethod("getStaticValue");
	String staticValue = (String) getStaticValue.invoke(c);
	System.out.println("Results from getStaticValue: " + staticValue);

	// invoke static method on instance
        staticValue = (String) getStaticValue.invoke(o);
        // actually, no need to give obj ref, null works just fine for static methods
	// staticValue = (String) getStaticValue.invoke(null);
	System.out.println("Results from getStaticValue: " + staticValue);

	// get method with parameters
	Method doWork = c.getMethod("doWork", String.class, int.class, boolean.class);
	doWork.invoke(o, "Hi", 1, true);

	// reflection call does autoboxing
	doWork.invoke(o, "Hi", new Integer(2), new Boolean(false));

	// Reflection will not coerce args to the correct types. The following
	// call fails with IllegalArgumentException.
	// doWork.invoke(o, "Hi", "1", "true");
    }

    public String getValue() {
	return "value";
    }

    public static String getStaticValue() {
	return "static value";
    }

    public void doWork(String s, int i, boolean b) {
	System.out.printf("Doing work: string(%s), int(%s), boolean(%s)\n", s, i, b);
    }
}
Share |
| Comment  | Tags