gpt4 book ai didi

java - 如何在单例中通过字符串调用方法

转载 作者:行者123 更新时间:2023-12-01 13:07:18 25 4
gpt4 key购买 nike

我有一个单例类,带有方法名称的字符串,我想从此类调用该方法。

class Foo {
private static Foo instance;
private String name;
private Foo() { }
public static getInstance() {
if(instance == null) instance = new Foo();
return instance;
}
public Foo setName(String name) {
this.name = name;
return this;
}
private void bar() {
System.out.println("a");
}
public void execute() {
// invoke "name" method here
}
}

Foo.getInstance().setName("bar").execute();

我该怎么做?

最佳答案

使用Foo.getClass().getMethod(name, null).invoke(this, null)

如果您有多个名称相同但签名不同的方法,则需要更改 getMethod 的第二个参数;如果方法接受参数,则需要更改 invoke 的第二个参数。

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

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