我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
当前回答
仅适用于这种情况-
在调用equals方法之前不检查变量是否为空(下面的字符串比较示例):
if ( foo.equals("bar") ) {
// ...
}
如果foo不存在,将导致NullPointerException。
如果这样比较字符串,可以避免这种情况:
if ( "bar".equals(foo) ) {
// ...
}
其他回答
问这个问题表明你可能对错误处理策略感兴趣。如何以及在哪里处理错误是一个普遍存在的体系结构问题。有几种方法可以做到这一点。
我最喜欢的是:允许异常在“主循环”或其他具有适当职责的函数中波动-捕获它们。检查错误情况并适当处理它们可以被视为一项专门的责任。
当然,也要看看面向方面编程——它们有很好的方法将if(o==null)handleNull()插入到字节码中。
有一种很好的方法来检查JDK中的空值。Optional.java有大量解决这些问题的方法。例如:
/**
* Returns an {@code Optional} describing the specified value, if non-null,
* otherwise returns an empty {@code Optional}.
*
* @param <T> the class of the value
* @param value the possibly-null value to describe
* @return an {@code Optional} with a present value if the specified value
* is non-null, otherwise an empty {@code Optional}
*/
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
/**
* Return {@code true} if there is a value present, otherwise {@code false}.
*
* @return {@code true} if there is a value present, otherwise {@code false}
*/
public boolean isPresent() {
return value != null;
}
/**
* If a value is present, invoke the specified consumer with the value,
* otherwise do nothing.
*
* @param consumer block to be executed if a value is present
* @throws NullPointerException if value is present and {@code consumer} is
* null
*/
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
帮助标枪真的非常非常有用。
如果您认为对象不应为空(或是错误),请使用断言。如果您的方法不接受null参数,请在javadoc中说它并使用断言。
您必须检查对象!=仅当您想处理对象可能为空的情况时才为空。。。
有人建议在Java7中添加新注释,以帮助处理null/notnull参数:http://tech.puredanger.com/java7/#jsr308
我们一直在使用Apache库(Apache Commons)解决这个问题。
ObjectUtils.equals(object, null)
or
CollectionUtils.isEmpty(myCollection);
or
StringUtils.isEmpty("string");
作为一种实践,我喜欢前面的回答,即为集合提供初始默认值或空集,以最小化需要。
这些可以是防止出现NullPointerException或使用空集合的简单用法。这并不能回答如何处理空对象的问题,但它们为对象或集合的基本验证提供了一些检查。
希望这有帮助。
除了使用assert,还可以使用以下命令:
if (someobject == null) {
// Handle null here then move on.
}
这略好于:
if (someobject != null) {
.....
.....
.....
}