我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
当前回答
这是大多数开发人员最常见的错误。
我们有很多方法来处理这个问题。
方法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;
}
其他回答
Java8带来了新的Java.util.Optional类,它可以解决一些问题。至少可以说,它提高了代码的可读性,并且在公共API的情况下,使API的契约对客户端开发人员更加清晰。
它们是这样工作的:
给定类型(Fruit)的可选对象被创建为方法的返回类型。它可以是空的或包含Fruit对象:
public static Optional<Fruit> find(String name, List<Fruit> fruits) {
for (Fruit fruit : fruits) {
if (fruit.getName().equals(name)) {
return Optional.of(fruit);
}
}
return Optional.empty();
}
现在看看这段代码,我们在其中搜索给定Fruit实例的Fruit(水果)列表:
Optional<Fruit> found = find("lemon", fruits);
if (found.isPresent()) {
Fruit fruit = found.get();
String name = fruit.getName();
}
您可以使用map()运算符对可选对象执行计算,或从中提取值。orElse()允许您为缺少的值提供回退。
String nameOrNull = find("lemon", fruits)
.map(f -> f.getName())
.orElse("empty-name");
当然,检查空/空值仍然是必要的,但至少开发人员意识到该值可能是空的,忘记检查的风险是有限的。
在从头开始使用Optional构建的API中,只要返回值可能为空,并且仅在不能为空时返回纯对象(惯例),客户端代码可能会放弃对简单对象返回值的空检查。。。
当然,Optional也可以用作方法参数,在某些情况下,可能比5或10个重载方法更好地指示可选参数。
可选提供了其他方便的方法,例如允许使用默认值的orElse,以及与lambda表达式一起使用的ifPresent。
我邀请您阅读这篇文章(我撰写这个答案的主要来源),其中很好地解释了NullPointerException(以及一般的空指针)问题以及Optional带来的(部分)解决方案:Java Optional Objects。
如果您使用的是java8或更高版本,请从java.util.Objects获取isNull(yourObject)。
示例:-
String myObject = null;
Objects.isNull(myObject); //will return true
用法:以下代码返回非空值(如果名称不为空,则返回该值,否则返回默认值)。
final String name = "Jobin";
String nonNullValue = Optional.ofNullable(name).orElse("DefaultName");
问这个问题表明你可能对错误处理策略感兴趣。如何以及在哪里处理错误是一个普遍存在的体系结构问题。有几种方法可以做到这一点。
我最喜欢的是:允许异常在“主循环”或其他具有适当职责的函数中波动-捕获它们。检查错误情况并适当处理它们可以被视为一项专门的责任。
当然,也要看看面向方面编程——它们有很好的方法将if(o==null)handleNull()插入到字节码中。
你有一个选择
在方法上使用checker框架的@RequiresNonNull。对于ex,如果使用null参数调用一个注释为null的方法,就会得到这个结果。它将在编译期间失败,甚至在代码运行之前!因为在运行时它将是NullPointerException@RequiresNonNull(值={“#1”})静态空隙检查(布尔x){如果(x)System.out.println(“true”);else System.out.println(“false”);}公共静态void main(String[]参数){检查(空);}
得到
[ERROR] found : null
[ERROR] required: @Initialized @NonNull Boolean
[ERROR] -> [Help 1]
还有其他方法,如Use Java 8‘s Optional、Guava Annotations、Null Object pattern等。只要您达到避免的目标,就无所谓了=无效的
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()来删除所有前导和尾随空格字符。