检查多个变量java中的替换空值 [英] Check an replace null values in multiple variables java

查看:66
本文介绍了检查多个变量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.

这篇关于检查多个变量java中的替换空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆