import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
String a = "testa";
String b = "testb";
call(a);
call(b, "hello");
}
private static void call(String methodName) {
try {
Method m = Test.class.getDeclaredMethod(methodName);
m.invoke(Test.class);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void call(String methodName, String param) {
try {
Method m = Test.class.getDeclaredMethod(methodName, String.class);
m.invoke(Test.class, param);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testa() {
System.out.println("无参数");
}
public static void testb(String c) {
System.out.println(c);
}
}
通过方法名动态调用方法
最新推荐文章于 2023-05-23 09:00:43 发布