java 检查多个变量java中的替换空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28199856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check an replace null values in multiple variables java
提问by user1795370
I'm trying to find an easy way to perform multiple null checks/ replacements in multiple variables in Java.
我试图找到一种简单的方法来在 Java 中的多个变量中执行多个空检查/替换。
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.
我有一个包含大约 20 个字符串变量的对象。在构造函数中,我想检查是否有任何变量值为空。如果它们为空,我想用空字符串替换它们。我可以执行一系列 if 语句,但我觉得必须有一种更简洁的方法来做到这一点。
回答by aioobe
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
除非你想诉诸反射(我强烈反对)你最好的办法可能是创建一个辅助方法(return s == null ? "" : s
)并做
field1 = nullToEmpty(field1);
field2 = nullToEmpty(field2);
...
If you already depend on Apache Commons or Guava you can use StringUtils.defaultString
or Strings.nullToEmpty
.
如果您已经依赖 Apache Commons 或 Guava,则可以使用StringUtils.defaultString
或Strings.nullToEmpty
。
回答by Nantoka
I agree with aioobe, using reflection is something you should avoid like the plague. But if you are blessed with a project where for example you have to mock a REST interface manually and the objects that come via this interface have tons of Integer, String, Double etc. inside I think you have no other choice.
我同意 aioobe,使用反射是你应该避免的事情,就像瘟疫一样。但是如果你有一个项目,例如你必须手动模拟一个 REST 接口,并且通过这个接口来的对象里面有大量的 Integer、String、Double 等,我认为你别无选择。
Here is a generic method that replaces all null pointers it can find in an object with its scalar default values, fills String fields with an empty string and does so recursively if the objects it finds have a parameterless default constructor. Hope this helps other people in the same situation as well.
这是一个通用方法,它用它的标量默认值替换它可以在对象中找到的所有空指针,用空字符串填充 String 字段,如果它找到的对象具有无参数的默认构造函数,则递归执行此操作。希望这也能帮助处于相同情况的其他人。
static void fillNullObjects(Object object) {
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
if (field.get(object) != null) {
continue;
}
else if (field.getType().equals(Integer.class)) {
field.set(object, 0);
}
else if (field.getType().equals(String.class)) {
field.set(object, "");
}
else if (field.getType().equals(Boolean.class)){
field.set(object, false);
}
else if (field.getType().equals(Character.class)) {
field.set(object, '\u0000');
}
else if (field.getType().equals(Byte.class)) {
field.set(object, (byte) 0);
}
else if (field.getType().equals(Float.class)) {
field.set(object, 0.0f);
}
else if (field.getType().equals(Double.class)) {
field.set(object, 0.0d);
}
else if (field.getType().equals(Short.class)) {
field.set(object, (short) 0);
}
else if (field.getType().equals(Long.class)) {
field.set(object, 0L);
}
else if (field.getType().getDeclaredFields().length > 0){
for (Constructor<?> constructor : field.getClass().getConstructors()) {
if (constructor.getParameterTypes().length == 0) {
field.set(object, constructor.newInstance());
fillNullObjects(field.get(object));
}
}
}
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
回答by jmcg
Check out Apache Commons' StringUtils
查看 Apache Commons' StringUtils
StringUtils.defaultString(yourString)
This replaces null
s with an empty String. Or you can define your own replacement:
这将null
s替换为空字符串。或者您可以定义自己的替换:
StringUtils.defaultString(null, "foo") // returns "foo"
回答by TheFaster
public static String checkNull (String inputString){
if(inputString == null){
inputString = "";
}
return inputString;
}
And just call that whenever you want to check a string.
只要你想检查一个字符串就调用它。
回答by Thomas H
Store your variables in an array (or list, if you don't know exacty the number of variables but I don't think so) and loop over it
将您的变量存储在一个数组(或列表,如果您不知道变量的确切数量,但我不这么认为)中并循环遍历它
String[] variables;
//...
for(int i = 0; i < variables.length; i++)
if(variables[i] == null) variables[i] = "";
回答by Simon
20 field variables sounds like an egregious case. You should try to avoid explicitly handling that many variables in any situation, or at least factor the code so they are only ever explicitly listed in one place.
20 个字段变量听起来像是一个令人震惊的案例。您应该尽量避免在任何情况下显式处理这么多变量,或者至少考虑代码,以便它们只在一个地方显式列出。
A common pattern is to associate each variable with an enumeration, and use the enumeration as a key in a Map with type Enum -> String, or use the enumeration's ordinal as an index into a String array that is sized to the Enumeration value.
一个常见的模式是将每个变量与一个枚举相关联,并将枚举用作类型为 Enum -> String 的 Map 中的键,或者使用枚举的序数作为字符串数组的索引,该数组的大小为枚举值。
Like so:
像这样:
public enum StringProperties {
TTL, RECVBUF, SENDBUF, RETRIES, ... ;
}
If you wanted explicit default values, you can couple an enumeration with a number of parameters:
如果您想要明确的默认值,您可以将枚举与多个参数结合使用:
public enum StringProperties {
TTL ("100"),
RECVBUF ("1024"),
SENDBUF ("1500"),
RETRIES ("10"),
...
;
public String getDefaultValue() { ... }
}
This strategy means that your code needs minimal modification if you need to add/remove a property, or change a default value.
此策略意味着如果您需要添加/删除属性或更改默认值,则您的代码需要最少的修改。
In your (copy constructor?) case, you can loop over the enumeration values with something like:
在您的(复制构造函数?)情况下,您可以使用以下内容循环枚举值:
for (StringProperties property : StringProperties.values()) {
if (obj.getProperty(property) != null) {
// handle present case
...
} else {
// handle default storage case
...
}
}
Or, like thomas said, you can use a String array on its own, but this assumes that you don't need a way to address each String.
或者,就像 thomas 所说,您可以单独使用 String 数组,但这假设您不需要一种方法来寻址每个 String。
回答by wypieprz
For each field use the standard Java method:
对于每个字段使用标准的 Java 方法:
Objects.toString(field, "");
Avoid constructor with a large number of fields if possible. Use Builderinstead (as suggested in Effective Java, Item 2: Consider a builder when faced with many constructor parameters).
如果可能,请避免具有大量字段的构造函数。改用Builder(如Effective Java,第 2 项:当面临许多构造函数参数时考虑使用构建器)中的建议。