我遇到了一个问题。我主要从java中的命令行参数接收3种类型的输入。基于这三个输入,我需要调用各自的方法(我为每个输入定义了 3 个方法)。
条件是:我们不应该使用if,switch,条件运算符,while语句,反射
任何人请分享您的想法
您可以使用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);
如果要在Map
中找不到输入x
时调用默认方法,则可以使用getOrDefault
而不是get
:
methods.getOfDefault(x, a -> System.out.println("cannot process input " + a)).accept(input);
您可以使用具有通用方法的接口
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();
}
}