如何使用字符串调用方法

gml*_*yra 3 java oop string

我正在尝试使用字符串来调用方法?

假设我有一个名为的类Kyle,它有 3 个方法:

public void Test();
public void Ronaldo();
public void MakeThis();
Run Code Online (Sandbox Code Playgroud)

我有一个字符串,其中包含我需要调用的方法的名称:

String text = "Test()";
Run Code Online (Sandbox Code Playgroud)

现在我需要调用名称在此字符串内的方法:

Kyle k = new Kyle();
Run Code Online (Sandbox Code Playgroud)

k.text;

pb2*_*b2q 5

您需要使用 javaReflection来执行此操作。

请参阅:Class.getMethod()

使用您的具体示例:

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);
Run Code Online (Sandbox Code Playgroud)

getMethod()这不包括和所需的异常处理Method.invoke(),并且仅涵盖调用不带参数的方法的情况。

也可以看看: