我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
当前回答
如果您认为对象不应为空(或是错误),请使用断言。如果您的方法不接受null参数,请在javadoc中说它并使用断言。
您必须检查对象!=仅当您想处理对象可能为空的情况时才为空。。。
有人建议在Java7中添加新注释,以帮助处理null/notnull参数:http://tech.puredanger.com/java7/#jsr308
其他回答
public class Null {
public static void main(String[] args) {
String str1 = null;
String str2 = "";
if(isNullOrEmpty(str1))
System.out.println("First string is null or empty.");
else
System.out.println("First string is not null or empty.");
if(isNullOrEmpty(str2))
System.out.println("Second string is null or empty.");
else
System.out.println("Second string is not null or empty.");
}
public static boolean isNullOrEmpty(String str) {
if(str != null && !str.isEmpty())
return false;
return true;
}
}
输出
str1 is null or empty.
str2 is null or empty.
在上面的程序中,我们有两个字符串str1和str2。str1包含空值,str2为空字符串。
我们还创建了一个函数isNullOrEmpty(),顾名思义,它检查字符串是空还是空。它使用!=进行空检查null和字符串的isEmpty()方法。
简单地说,如果字符串不是null并且isEmpty()返回false,那么它既不是null也不是空的。否则,就是这样。
但是,如果字符串只包含空白字符(空格),则上述程序不会返回空。从技术上讲,isEmpty()看到它包含空格并返回false。对于带空格的字符串,我们使用string方法trim()来删除所有前导和尾随空格字符。
您可以考虑空对象是bug的情况,而不是空对象模式(有其用途)。
当抛出异常时,检查堆栈跟踪并解决错误。
我们一直在使用Apache库(Apache Commons)解决这个问题。
ObjectUtils.equals(object, null)
or
CollectionUtils.isEmpty(myCollection);
or
StringUtils.isEmpty("string");
作为一种实践,我喜欢前面的回答,即为集合提供初始默认值或空集,以最小化需要。
这些可以是防止出现NullPointerException或使用空集合的简单用法。这并不能回答如何处理空对象的问题,但它们为对象或集合的基本验证提供了一些检查。
希望这有帮助。
就我个人而言,我要么同意jim nelson的答案,要么如果我确实发现空检查对于特定的上下文是方便的,我会将lombok合并到我的项目中,并使用@NonNull注释。
例子:
import lombok.NonNull;
public class NonNullExample extends Something {
private String name;
public NonNullExample(@NonNull Person person) {
super("Hello");
this.name = person.getName();
}
}
甚至在@NonNull序言中也提到:
或者:我是如何学会停止担心并爱上NullPointerException的。
对于Java8或更新版本,最好的选择可能是使用Optional类。
Optional stringToUse = Optional.of("optional is there");
stringToUse.ifPresent(System.out::println);
这对于可能的空值的长链来说尤其方便。例子:
Optional<Integer> i = Optional.ofNullable(wsObject.getFoo())
.map(f -> f.getBar())
.map(b -> b.getBaz())
.map(b -> b.getInt());
如何在null上引发异常的示例:
Optional optionalCarNull = Optional.ofNullable(someNull);
optionalCarNull.orElseThrow(IllegalStateException::new);
Java7引入了Objects.requireOnNull方法,当需要检查某些内容是否为非空时,该方法非常方便。例子:
String lowerVal = Objects.requireNonNull(someVar, "input cannot be null or empty").toLowerCase();