import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
* 方法的调用
*/
public class CallMethod {
public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class invokeTesterClass=Class.forName("InvokeTester");
//相当于Object obj= new InvokeTester();
Object obj=invokeTesterClass.newInstance();
//这里的String.class是指echo方法的参数类型
Method method=invokeTesterClass.getDeclaredMethod("echo",String.class);
String result=(String)method.invoke(obj, "java");
System.out.println(result);
}
}
class InvokeTester {
public int add(int param1, int param2) {
return param1 + param2;
}
public String echo(String msg) {
return "echo:" + msg;
}
public String echo() {
return "echo";
}
}
输出:echo:java
续
Class> c = Class.forName("类名");
Class>[] paraTypes = new Class[]{para1.class, para2.class};
Object[] paraValues = new Object[]{para1, para2};
Method m = c.getMethod("方法名", paraTypes);
return (Boolean) m.invoke(c.newInstance(), paraValues);