java - 返回具有任意数量输入参数的函数
问题描述
我的代码需要通过各种辅助类预先检查一系列复杂的正则表达式。然后,如果一切正常,它需要以事后检查的方式执行一系列函数调用。如果案例构造没有捕获到某些内容,我需要将其记录下来以备后用。
我试图避免有两个重复的大喇叭if
。
我在想,如果大if
语句(或switch
)要返回一个函数,我可以检查返回的函数是否为空来进行预检查。如果它为空,我也可以记录它。如果它不为空,我可以直接调用它。这样我就不需要在代码的两个部分中进行复杂的逻辑检查。
我在想一些事情:
class Playground {
public static Function getFunction(String condition) {
switch (condition) {
case "one":
return Function one(1);
case "two":
return Function two("two",2);
default:
return null;
}
}
public static void one(int i) {
System.out.println("one: i: " + i);
}
public static void two(String s, int i) {
System.out.println("two: s: " + s + " i: " + i);
}
public static void main(String[ ] args) {
Function f1 = getFunction("one");
Function f2 = getFunction("two");
f1();
f2();
}
}
但我不能完全正确地理解语法。
有人可以告诉我这在 Java 中是否可行?如果是这样,也许有人可以就语法更正提出建议。
- 所有调用的方法都将返回 void。
- 它们将是实例调用而不是静态方法。
- 返回的函数可能有不同数量的输入参数。当该方法被调用时,我也需要以某种方式进行设置。
如果没有这样的方法,是否有替代方案,也许是设计模式,可能会有所帮助?(除了将复杂的 if 语句映射到整数之类的东西。如果没有匹配,则为 0,否则您有值。然后您将有另一个基于 int 的开关。)
解决方案
看起来您想返回一个调用方法的 Runnable:
class Playground{
public static Runnable getRunnable(String condition) {
switch (condition) {
case "one":
return () -> one(1);
case "two":
return () -> two("two", 2);
default:
return null;
}
}
public static void one(int i) {
System.out.println("one: i: " + i);
}
public static void two(String s, int i) {
System.out.println("two: s: " + s + " i: " + i);
}
public static void main(String[ ] args) {
Runnable f1 = getRunnable("one");
Runnable f2 = getRunnable("two");
Runnable f3 = getRunnable("three");
f1.run();
f2.run();
if (f3 == null) {
System.out.println("none");
}
}
}
推荐阅读
- makefile - 编译tbb项目时出现cmake命令问题
- pine-script - 如何隐藏 RSI 条上的彩色零
- python - 我认为为什么会出现这种词性错误,我该如何解决
- ios - 给定一个自定义形状,如何增加尺寸以适应 SwiftUI 中的框架?
- python - 如何使用python在默认程序中打开多个文件
- javascript - 如何使用 Cognito 在 AWS Amplify Vuejs 应用程序中检查当前用户并加载用户数据
- java - 如何反转一个整数?
- javascript - 检查或统计所选文件少于 2 个
- javascript - ChartJs:如何在自动跳过设置为 true 时强制显示标签
- javascript - 在使用 tablesorter 排序的表中使用输入元素时,如何使用 inputmask 获取输入元素以不将更改恢复为先前的值?