我想通过使用字符串来调用方法.我知道这是可能的; 从我的理解,反思是要走的路.但是,我很难让它工作,这就是我想要的.
例如:
String method ="punch";
int punch(){
return 1;
}
Run Code Online (Sandbox Code Playgroud)
我想通过字符串名称调用该方法.有人能告诉我一个例子吗?
public class foo {
String method ="punch";
int punch() {
return 1;
}
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> myClass = Class.forName("foo");
Method myMethod = myClass.getMethod("punch");
Object retObject = myMethod.invoke(null);
}
}
Run Code Online (Sandbox Code Playgroud)
我需要做什么才能得到1号?
java ×1