我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
当前回答
除了使用assert,还可以使用以下命令:
if (someobject == null) {
// Handle null here then move on.
}
这略好于:
if (someobject != null) {
.....
.....
.....
}
其他回答
我遵循以下准则以避免空检查。
尽可能避免成员变量的延迟初始化。初始化声明本身中的变量。这将处理NullPointerExceptions。在周期早期决定成员变量的可变性。有效地使用像final关键字这样的语言结构。如果您知道不会更改方法的扩充,请将它们声明为final。尽可能限制数据的变异。某些变量可以在构造函数中创建,并且永远无法更改。删除公共setter方法,除非确实需要它们。例如,假设应用程序中的一个类(A.java)正在维护HashMap这样的集合。不要在A.java中提供公共getter方法,而允许B.java直接在Map中添加元素。而是在A.java中提供一个API,它将一个元素添加到集合中。//避免a.getMap().put(键,值)//推荐的public void addElement(对象键,对象值){//在此处对键和值进行空检查:单个位置map.put(键,值);}最后,在正确的位置有效地使用try{}catch{}finally{}块。
使用Java8,您可以将供应商传递给下面这样的助手方法,
if(CommonUtil.resolve(()-> a.b().c()).isPresent()) {
}
上面的代码替换了下面的锅炉板代码,
if(a!=null && a.b()!=null && a.b().c()!=null) {
}
//通用工具.java
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
} catch (NullPointerException var2) {
return Optional.empty();
}
}
就我个人而言,我要么同意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的。
我可以更笼统地回答吗!
当方法以我们不期望的方式获取参数时,我们通常会遇到这个问题(错误的方法调用是程序员的错误)。例如:您希望得到一个对象,而得到一个null。您希望得到一个至少包含一个字符的字符串,而得到一个空字符串。。。
因此:
if(object == null){
//you called my method badly!
}
or
if(str.length() == 0){
//you called my method badly again!
}
他们都希望在执行任何其他函数之前确保我们收到了有效的参数。
如其他一些答案中所述,为了避免上述问题,您可以遵循契约设计模式。请参见http://en.wikipedia.org/wiki/Design_by_contract.
要在java中实现这种模式,可以使用javax.annotation.NotNull等核心java注释,或者使用Hibernate Validator等更复杂的库。
只是一个示例:
getCustomerAccounts(@NotEmpty String customerId,@Size(min = 1) String accountType)
现在,您可以安全地开发方法的核心函数,而无需检查输入参数,它们可以保护您的方法不受意外参数的影响。
您可以更进一步,确保在应用程序中只能创建有效的pojo。(来自hibernate验证器站点的示例)
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
// ...
}
有一种很好的方法来检查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);
}
帮助标枪真的非常非常有用。