如何在不使用if,switch,条件运算符,反射,while语句的情况下调用不同的方法

时间:2018-02-04 11:06:17

标签: java

我遇到了问题..我主要从java..say A,B,C中的命令行参数接收3种类型的输入。基于这三个输入,我需要调用相应的方法(我有3个方法定义一个用于每个输入)。

条件是:我们不应该使用if,switch,条件运算符,while语句,反射

任何人请分享您的想法

2 个答案:

答案 0 :(得分:2)

您可以使用Map将3种可能的输入映射到3种相应的方法。

例如,假设输入为String,要执行的逻辑是接受String的方法:

Map<String,Consumer<String>> methods = new LinkedHashMap<>();
methods.put("A",a->methodA(a));
methods.put("B",a->methodB(a));
methods.put("C",a->methodC(a));

现在,给定输入x,您可以使用

调用所需的方法
methods.get(x).accept(input);

如果您希望在getOrDefault中找不到输入get时调用默认方法,则可以使用x代替Map

methods.getOfDefault(x, a -> System.out.println("cannot process input " + a)).accept(input);

答案 1 :(得分:1)

您可以使用具有常用方法的界面

import java.util.*;

interface A{
    public void run();
}
public class MyClass implements A{

    public static void method1() { System.out.println("method1"); }
    public static void method2() { System.out.println("method2"); } 
    public static void method3() { System.out.println("method3"); }
    public void run(){}
    public static void main(String [] args){
        A method1 = new A() { 
            public void run() { method1(); } 
        };
        A method2 = new A() {
            public void run() { method2(); } 
        };
        A method3 = new A() {
            public void run() { method3(); } 
        };

        Map<String, A> methodMap = new HashMap<String, A>();
        methodMap.put(args[0], method1);
        methodMap.put(args[1], method2);
        methodMap.put(args[2], method3);

        A a = methodMap.get(args[0]);
        a.run();
    }
}