我使用x!=null以避免NullPointerException。还有其他选择吗?

if (x != null) {
    // ...
}

当前回答

你有一个选择

在方法上使用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等。只要您达到避免的目标,就无所谓了=无效的

其他回答

Java8在Java.util包中引入了一个新的类Optional。它用于表示值是否存在。这种新构造的主要优点是不再有太多的空检查和NullPointerException。它避免了任何运行时NullPointerExceptions,并支持我们开发干净整洁的Java API或应用程序。与集合和数组一样,它也是一个最多只能容纳一个值的容器。

下面是一些有用的链接,您可以关注

https://www.mkyong.com/java8/java-8-optional-in-depth/

https://dzone.com/articles/java-8-optional-avoid-null-and

我可以更笼统地回答吗!

当方法以我们不期望的方式获取参数时,我们通常会遇到这个问题(错误的方法调用是程序员的错误)。例如:您希望得到一个对象,而得到一个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;

   // ...
}

这是大多数开发人员最常见的错误。

我们有很多方法来处理这个问题。

方法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或更新版本,最好的选择可能是使用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();

我喜欢Nat Pryce的文章。以下是链接:

用多态调度避免空值避免使用“告诉,不要问”风格的null

在文章中,还有一个指向Java Maybe Type的Git存储库的链接,我觉得这很有趣,但我不认为单独使用它会降低检查代码膨胀。在互联网上做了一些研究之后,我想主要通过仔细设计可以减少空码膨胀。