我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
当前回答
有时,您可以使用对其参数进行操作的方法来定义对称操作:
a.f(b); <-> b.f(a);
如果你知道b永远不可能为空,你可以交换它。它对equals最有用:而不是foo.equals(“bar”);最好使用“bar”。equals(foo);。
其他回答
对于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();
有一种很好的方法来检查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);
}
帮助标枪真的非常非常有用。
Guava是Google提供的一个非常有用的核心库,它有一个很好且有用的API来避免空值。我发现UsingAndAvoidingNullExplain非常有用。
正如wiki中所解释的:
可选<T>是用非空值。可选可以包含非空T引用(在这种情况下,我们称引用为“present”),或者它可能包含什么都没有(在这种情况下,我们说引用“不存在”)。从来没有称为“包含null”
用法:
Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
如果不允许空值
如果从外部调用方法,请从以下内容开始:
public void method(Object object) {
if (object == null) {
throw new IllegalArgumentException("...");
}
然后,在该方法的其余部分中,您将知道该对象不为空。
如果它是一个内部方法(不是API的一部分),只需记录它不能为空,就可以了。
例子:
public String getFirst3Chars(String text) {
return text.subString(0, 3);
}
但是,如果您的方法只是传递值,而下一个方法传递值等,则可能会出现问题。在这种情况下,您可能需要检查上述参数。
如果允许为空
这真的取决于。如果发现我经常这样做:
if (object == null) {
// something
} else {
// something else
}
所以我分支,做两件完全不同的事情。没有难看的代码片段,因为我确实需要根据数据做两件不同的事情。例如,我应该处理输入,还是应该计算一个好的默认值?
实际上,我很少使用“if(object!=null&&…”这个成语。
如果你展示了你通常使用这个习语的例子,那么给你举例可能会更容易。
您还可以使用CheckerFramework(带有JDK7及更高版本)静态检查空值。这可能会解决很多问题,但需要运行一个目前仅适用于OpenJDK AFAIK的额外工具。https://checkerframework.org/