您的 switch 语句中必须有常量,这样您指定的内容将不起作用。作为一个例子,你可以做这样的事情。您不仅限于使用 Runnable lambdas。可以使用任何功能接口,并在调用时提供适当的参数。
请注意,允许调用 any 类的 any 方法不是一个好主意,因为它可能会导致意外结果或安全问题,具体取决于它的使用方式。
public class ThisClass {
public static void main(String[] args) {
Map<String, Runnable> map = new HashMap<>();
ThisClass tc = new ThisClass();
map.put("A", () -> tc.doOneThing());
map.put("B", () -> tc.doAnotherThing());
map.put("C", () -> tc.doAthirdThing());
map.put("D", () -> tc.doSomethingElse());
for (String str : new String[] { "A", "B", "Q", "C", "D", "E" }) {
map.getOrDefault(str, () -> tc.defaultMethod()).run();
}
}
public void doOneThing() {
System.out.println("Doing one thing");
}
public void defaultMethod() {
System.out.println("Executing default");
}
public void doAnotherThing() {
System.out.println("Doing Another thing");
}
public void doAthirdThing() {
System.out.println("Doing a third thing");
}
public void doSomethingElse() {
System.out.println("Doing something Else");
}
}
打印
Doing one thing
Doing Another thing
Executing default
Doing a third thing
Doing something Else
Executing default
你也可以这样做。
Map<String, DoubleBinaryOperator> map = new HashMap<>();
map.put("+", (a, b) -> a + b);
map.put("-", (a, b) -> a - b);
map.put("*", (a, b) -> a * b);
map.put("/", (a, b) -> a / b);
DoubleBinaryOperator error = (a, b) -> {
throw new IllegalArgumentException();
};
for (String str : new String[] { "+", "-", "L", "/", "*" }) {
try {
double result = map.getOrDefault(str, error)
.applyAsDouble(2.0, 3.0);
System.out.println("result = " + result);
} catch (IllegalArgumentException iae) {
System.out.println("unknown operator \"" + str + "\"");
}
}
打印
result = 5.0
result = -1.0
unknown operator "L"
result = 0.6666666666666666
result = 6.0