提问人:Chethan Swaroop 提问时间:6/3/2020 最后编辑:GameDroidsChethan Swaroop 更新时间:6/3/2020 访问量:3446
如何在 Java 中变量不为 null 时才将变量作为参数传递
How to pass variables as arguments only if it is not null in Java
问:
我有以下代码存根,我正在从属性文件中读取一组值。 我需要使用这些值将其作为参数传递给函数,前提是它们不是 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) {
}
在上面的代码片段中。我想使用参数 arg1、arg2、arg4 调用 testMethod(),只是因为 arg3 为 NULL。
参数的数量可能会有所不同。它不会一直都是 4。
我的代码应该动态检查参数是否为 NULL 并将其传递给 testMethod()。
我可以在 Java 中实现这一点吗?如果是,有人可以帮我吗?
答:
7赞
Piotr Wilkin
6/3/2020
#1
是的,有多种方法可以做到这一点,因为语法基本上是传递参数数组的缩写。因此,一种方法是例如:...
testMethod(Arrays.stream(args).filter(Objects::nonNull).toArray(String[]::new))
2赞
Natan Ziv
6/3/2020
#2
您可以创建一个列表,并用不为 null 的字符串填充它,如果列表不为空,则传递该列表。
2赞
F. Malato
6/3/2020
#3
您应该创建一个包含所有参数的列表,遍历它以检查它,然后将列表传递给 。String
null
testMethod()
以下是我的意思的片段:
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);
}
评论
testMethod(String... values)
null