Che*_*oop 0 java parameter-passing
我有以下代码存根,我正在从属性文件中读取一组值。仅当它们不为 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) {
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码片段中。我想用参数 arg1、arg2、arg4 调用 testMethod() 只是因为 arg3 为 NULL。
参数的数量可能会有所不同。它不会一直是 4。
我的代码应该动态检查参数是否为 NULL 并将其传递给 testMethod()。
我可以在 Java 中实现这一点吗?如果是,有人可以帮助我..
是的,有多种方法可以做到这一点,因为...语法基本上是传递参数数组的缩写。因此,执行此操作的一种方法是:
testMethod(Arrays.stream(args).filter(Objects::nonNull).toArray(String[]::new))
| 归档时间: |
|
| 查看次数: |
1211 次 |
| 最近记录: |