Return 具有任意数量输入参数的函数

Return a function with an arbitrary number of input parameters

我的代码需要通过各种帮助程序预先检查一系列复杂的正则表达式 类。 然后,如果一切正常,它需要以 post-检查方式执行一系列函数调用。如果 case 构造没有捕捉到某些东西,我需要将其记录下来以备后用。

我正在努力避免出现两个重复的 if 语句。

我在想,如果大 if 语句(或 switch)是 return 函数,我可以检查 returned 函数是否为 null或不做预检查。如果它为空,我也可以记录它。如果它不为空,我可以直接调用它。这样我就可以避免在代码的两个部分进行复杂的逻辑检查。

我在想一些事情:

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 中是否可行?如果是这样,也许有人可以就语法更正提出建议。

如果没有这样的方法,是否有可能有帮助的替代方法,也许是设计模式? (除了将复杂的 if 语句映射到整数之类的东西之外。如果没有任何匹配,则为 0,否则你有值。然后你将有另一个基于 int 的开关。)

您似乎想要 return 一个调用方法的 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");
       }
    }
}