首页 > 解决方案 > 返回具有任意数量输入参数的函数

问题描述

我的代码需要通过各种辅助类预先检查一系列复杂的正则表达式。然后,如果一切正常,它需要以事后检查的方式执行一系列函数调用。如果案例构造没有捕获到某些内容,我需要将其记录下来以备后用。

我试图避免有两个重复的大喇叭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 中是否可行?如果是这样,也许有人可以就语法更正提出建议。

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

标签: javajava-8functional-programmingrunnable

解决方案


看起来您想返回一个调用方法的 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");
       }
    }
}

推荐阅读