我正在尝试使用字符串来调用方法?
假设我有一个名为 Kyle
的类,它有 3 个方法:
public void Test();
public void Ronaldo();
public void MakeThis();
我有一个字符串,其中包含我需要调用的方法的名称:
String text = "Test()";
现在我需要调用名称在此字符串内的方法:
Kyle k = new Kyle();
k.text;
?
最佳答案
您需要使用 java Reflection
来执行此操作。
使用您的具体示例:
String text = "Test";
Kyle k = new Kyle();
Class clas = k.getClass();
// you'll need to handle exceptions from these methods, or throw them:
Method method = clas.getMethod(text, null);
method.invoke(k, null);
这没有 getMethod()
和 Method.invoke()
所需的异常处理,并且仅涵盖调用不带参数的方法的情况。
另请参阅:
关于java - 如何使用字符串调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11108205/