Java reflection with Apache beanutils 

Joined:
03/07/2011
Posts:
57

May 24, 2011 15:59:41    Last update: May 24, 2011 15:59:41
Java reflection with Apache beanutils example.
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.beanutils.ConvertUtils;

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

	// instance method
	String value = (String) MethodUtils.invokeMethod(o, "getValue", null);
	System.out.println("Results from getValue: " + value);

	// static method
	String staticValue = (String) MethodUtils.invokeStaticMethod(c, "getStaticValue", null);
	System.out.println("Results from getStaticValue: " + staticValue);

	// invoke static method on instance
	staticValue = (String) MethodUtils.invokeMethod(o, "getStaticValue", null);
	System.out.println("Results from getStaticValue: " + staticValue);

	// get method with parameters
	MethodUtils.invokeMethod(o, "doWork", new Object[] {"Hi", new Integer(1), Boolean.TRUE});

	// beanutils does type convertion
	MethodUtils.invokeMethod(o, "doWork", new Object[] {
	    ConvertUtils.convert("Hi", Class.forName("java.lang.String")),
	    ConvertUtils.convert("1", Class.forName("java.lang.Integer")),
	    ConvertUtils.convert("true", Class.forName("java.lang.Boolean"))
	});
    }

    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