gpt4 book ai didi

java - 如何让类中的方法名动态化?

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

当我从类创建对象时,我想使类中的方法名称动态化,我想动态执行方法名称,下面是我的代码。

public static void ExecuteTest() throws Exception 
{
for (int i = 1, j = 1; i < 2; i = i+1, j = j+1) {
FW_ReadExcelFile N = new FW_ReadExcelFile();
FW_ReadExcelFile.setExcelSheetEnvValues(i,i);
//java.lang.String Flag2 = N.getTCExecuteFlag() ;

String Flag = "YES";
String Flag21 = N.getTCExecuteFlag();


if ( Flag.equals(Flag21) ){
String TCName = N.getTCName();
FW_Report u = new FW_Report();
u.TCName; // the FW_Report class has many methods and I want to call the method on my demand .
}

最佳答案

i want to execute the method name dynamically

使用Reflections in Java来实现这一目标。

示例代码:

        Class<?> name = Class.forName("ClassName");
Object instance = name.newInstance();
Method[] methods = name.getMethods();

for (Method method : methods) {
if (method.getName().equals(N.getTCName())) {
// Match found. Invoke the method. call the method on my demand.
method.invoke(instance, null);
break;
}
}

或者尝试一下:

       // Get the method name at runtime
Method method = ClassName.class.getMethod(N.getTCName(), null);
method.invoke(new ClassName(), null);

关于java - 如何让类中的方法名动态化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22143361/

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