检查多个变量java中的替换空值

问题描述:

我试图找到一种简单的方法来在 Java 中的多个变量中执行多个空检查/替换.

I'm trying to find an easy way to perform multiple null checks/ replacements in multiple variables in Java.

我有一个包含大约 20 个字符串变量的对象.在构造函数中,我想检查是否有任何变量值为空.如果它们为空,我想用空字符串替换它们.我可以执行一系列 if 语句,但我觉得必须有一种更简洁的方法来做到这一点.

I have an object with about 20 String variables. In the constructor I want to check if any of the variable values are null. If they are null I want to replace them with an empty String. I could perform a series of if statements but I feel like there must be a cleaner way to do this.

除非你想诉诸反射(我强烈反对),否则最好的办法可能是创建一个辅助方法(return s == null ?"" : s) 然后做

Unless you want to resort to reflection (which I strongly discourage) your best bet is probably to create a helper method (return s == null ? "" : s) and do

field1 = nullToEmpty(field1);
field2 = nullToEmpty(field2);
...

如果您已经依赖 Apache Commons 或 Guava,您可以使用 StringUtils.defaultStringStrings.nullToEmpty.

If you already depend on Apache Commons or Guava you can use StringUtils.defaultString or Strings.nullToEmpty.