【问题标题】:How to pass variables as arguments only if it is not null in Java仅当变量在Java中不为空时如何将变量作为参数传递
【发布时间】:2020-06-03 13:54:26
【问题描述】:

我有以下代码存根,我正在从属性文件中读取一组值。 仅当它们不为 NULL 时,我才需要使用这些值将其作为参数传递给函数。

public static void main(String[] args) {
    String arg1 = "arg1";
    String arg2 = "arg2";
    String arg3 = null;
    String arg4 = "arg4";
    .
    .
    .

    testMethod(arg1, arg2, arg3);
}

public void testMethod(String... values) {

}

在上面的代码中sn-p。我想用参数 arg1、arg2、arg4 调用 testMethod(),只是因为 arg3 为 NULL。

参数的数量可能会有所不同。不会一直是 4。

我的代码应该动态检查参数是否不为 NULL 并将其传递给 testMethod()。

我可以用 Java 实现吗?如果是,有人可以帮助我..

【问题讨论】:

  • 您可以做的是通过传递所有变量的数组来调用testMethod(String... values) 方法,在该方法中您可以手动检查变量是否为null 以及您想要的其他方法打电话。

标签: java parameter-passing


【解决方案1】:

是的,有多种方法可以做到这一点,因为... 语法基本上是传递参数数组的缩写。因此,执行此操作的一种方法是:

testMethod(Arrays.stream(args).filter(Objects::nonNull).toArray(String[]::new))

【讨论】:

    【解决方案2】:

    您可以创建一个列表并用不为空的字符串填充它,如果它不为空则传递该列表。

    【讨论】:

      【解决方案3】:

      您应该创建一个包含所有参数的String 列表,对其进行迭代以检查null,然后将列表传递给testMethod()

      这是我的意思的一个sn-p:

      public static void main(String[] args) {
          // This is only a simple example, you can make it way more efficient depending on your parameters
          List<String> arguments = new ArrayList<>(Arrays.asList("arg1", "arg2", null, "arg4", null, "arg5"));
          // This is what actually removes the "null" values
          arguments.removeAll(Collections.singletonList(null));
          // Then you can call your method
          testMethod(arguments);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-20
        • 1970-01-01
        • 1970-01-01
        • 2018-09-03
        相关资源
        最近更新 更多