JAVA:基于变量的值调用类方法

亚当·J

我正在用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");
   }

}

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

我尝试使用哈希图。我在其中为secondClass分配了键“ 1”。但是随后我将不得不强制转换该对象,但这使我回到最初的头痛,即不知道需要提前调用什么类。

因此,我尝试使用像这样的哈希图, HashMap<String, Object> map = new HashMap<String, Object>();

然后我可以执行map.get(“ 1”),但是现在我不能调用该类的任何方法。

如果需要使用较大的switch语句,则可以,但是我正在积极寻求更有效的替代方法。

老古巴顿(Curmudgeon)

您使用a是正确的,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();
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章