Java reflect invoke method code demo.
package com.foundjet.console;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.foundjet.bean.Person;
public class Program {
public static void main(String[] args) {
try {
testReflect();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void testReflect() throws IllegalAccessException, IllegalArgumentException
, InvocationTargetException, NoSuchMethodException, SecurityException {
//Class personClass = (Class)(Class.forName("com.foundjet.bean.Person"));
Person p = new Person();
p.setName("Bill");
p.setAge(20);
Class personClass = p.getClass();
Method getNameMethod = personClass.getMethod("getName");
Object result = getNameMethod.invoke(p);
System.out.println("getName(), result:" + result.toString());
}
}