我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
当前回答
Guava是Google提供的一个非常有用的核心库,它有一个很好且有用的API来避免空值。我发现UsingAndAvoidingNullExplain非常有用。
正如wiki中所解释的:
可选<T>是用非空值。可选可以包含非空T引用(在这种情况下,我们称引用为“present”),或者它可能包含什么都没有(在这种情况下,我们说引用“不存在”)。从来没有称为“包含null”
用法:
Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
其他回答
您可以为对象和字符串创建一个通用方法,以便在应用程序中完全使用它-这可以帮助您和您的同事:创建一个类,例如StringUtilities,并添加方法,例如getNullString
public static String getNullString(Object someobject)
{
if(null==someobject )
return null;
else if(someobject.getClass().isInstance("") &&
(((String)someobject).trim().equalsIgnoreCase("null")||
((String)someobject).trim().equalsIgnoreCase("")))
return null;
else if(someobject.getClass().isInstance(""))
return (String)someobject;
else
return someobject.toString().trim();
}
简单地将此方法称为,
if (StringUtilities.getNullString(someobject) != null)
{
//Do something
}
对于实用程序类,可以检查参数是否为空。
在所有其他情况下,您可能不必这样做。尽可能使用封装,从而减少您想检查null的地方。
Google集合框架为实现空检查提供了一种良好而优雅的方式。
库类中有一个方法如下:
static <T> T checkNotNull(T e) {
if (e == null) {
throw new NullPointerException();
}
return e;
}
用法是(使用import static):
...
void foo(int a, Person p) {
if (checkNotNull(p).getAge() > a) {
...
}
else {
...
}
}
...
或者在您的示例中:
checkNotNull(someobject).doCalc();
这是大多数开发人员最常见的错误。
我们有很多方法来处理这个问题。
方法1:
org.apache.commons.lang.Validate //using apache framework
notNull(对象对象,字符串消息)
方法2:
if(someObject!=null){ // simply checking against null
}
方法3:
@isNull @Nullable // using annotation based validation
方法4:
// by writing static method and calling it across whereever we needed to check the validation
static <T> T isNull(someObject e){
if(e == null){
throw new NullPointerException();
}
return e;
}
具有零安全性的Kotlin是一种优雅的选择,但它意味着更大的变化。