gpt4 book ai didi

JAVA:根据变量的值调用类方法

转载 作者:行者123 更新时间:2023-12-02 05:36:10 25 4
gpt4 key购买 nike

我正在开发一个 Java 项目,对这门语言和 OOP 还很陌生。我的困境是我想根据变量的值执行特定类的任务/函数。

这就是我想要实现的目标。

class mainClass{

String option;

public static void main(String[] args) {
mainClass main = new mainClass();
}

mainClass(){
secondClass sC = new secondClass();
thirdClass tC = new thirdClass();
switch (option){
case "1" :
sC.doSomething();
case "2" :
tC.doSomething();
}
}

}

class secondClass{
void doSomething(){
System.out.println("1");
}


}

class thirdClass{
void doSomething(){
System.out.println("2");
}

}

我不想这样做的原因是,如果我想添加第四个、第五个、第六个类等...我就必须更新开关。

我尝试使用 HashMap 。我将“1”的键分配给了 secondaryClass。但随后我就必须强制转换该对象,但这又让我回到了最初的头痛,即不知道需要提前调用哪个类。

然后我尝试使用这样的 HashMap , HashMap<String, Object> map = new HashMap<String, Object>();

然后我可以执行map.get("1"),但现在我无法调用相关类的任何方法。

如果我需要使用大型 switch 语句,我会的,但我正在积极寻找更有效的替代方案。

最佳答案

您使用 map 是正确的,但您在转换方面犹豫不决也是正确的。然而,现在使用泛型你可以解决所有这些问题:

interface DoesSomething {
// An object implementing this interface does something.
public void doSomething();
}

// Class that does something.
class FirstClass implements DoesSomething {

@Override
public void doSomething() {
// What FirstClass does.
}

}

// Another class that does something.
class SecondClass implements DoesSomething {

@Override
public void doSomething() {
// What SecondClass does.
}

}


// How I know what to do. Map the string to a DoesSomethng.
Map<String, DoesSomething> whatToDo = new HashMap<>();
{
// Populate my map.
whatToDo.put("1", new FirstClass());
whatToDo.put("2", new SecondClass());
}

public void doSomethingDependingOnSomething(String something) {
// Look up the string in the map.
DoesSomething toDo = whatToDo.get(something);
// Was it in there?
if (toDo != null) {
// Yes! Make it do it's thing.
toDo.doSomething();
}
}

关于JAVA:根据变量的值调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24944906/

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