gpt4 book ai didi

java - 如何使用字符串调用方法

转载 作者:行者123 更新时间:2023-12-01 19:53:23 24 4
gpt4 key购买 nike

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

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

public void Test();
public void Ronaldo();
public void MakeThis();

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

String text = "Test()";

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

Kyle k = new Kyle();

k.text;

最佳答案

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

参见: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);

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

另请参阅:

关于java - 如何使用字符串调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11108205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com