返回一个具有任意数量输入参数的函数。

问题描述 投票:2回答:1

我的代码需要通过各种帮助类对一系列复杂的regex进行预先检查,然后,如果一切正常,它需要以后检查的方式执行一系列函数调用。如果case构造没有捕捉到什么,我需要记录下来,以便以后使用。

我试图避免有两个巨大的重复的 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 return。
  • 它们将是实例调用而不是静态方法。
  • 返回的函数可能有不同数量的输入参数。当方法被调用时,我需要以某种方式将其也设置好。

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

java java-8 functional-programming runnable
1个回答
3
投票

看起来你想返回一个调用方法的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");
       }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.