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

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

当前回答

有一种很好的方法来检查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);
    }

帮助标枪真的非常非常有用。

其他回答

哇,当我们有57种不同的方式来推荐NullObject模式时,我几乎不想再加一个答案,但我想,一些对这个问题感兴趣的人可能想知道,有人提议为Java7添加“空安全处理”,这是一种精简的语法,如果不等于空逻辑的话。

Alex Miller给出的示例如下:

public String getPostcode(Person person) {  
  return person?.getAddress()?.getPostcode();  
}  

这个表示仅在左标识符不为空时取消引用,否则将表达式的其余部分求值为空。一些人,如Java Pose成员迪克·沃尔(Dick Wall)和德文郡的选民,真的很喜欢这个提议,但也有人反对,理由是它实际上会鼓励更多地使用null作为前哨值。


更新:在Project Coin下提交了一份关于Java 7中空安全运算符的官方提案。语法与上面的示例稍有不同,但概念相同。


更新:空安全运营商提议未纳入Project Coin。因此,您不会在Java7中看到这种语法。

函数方法可能有助于包装重复的空检查并执行匿名代码,如下面的示例。

    BiConsumer<Object, Consumer<Object>> consumeIfPresent  = (s,f) ->{
        if(s!=null) {
            f.accept(s);
        }
    };

    consumeIfPresent.accept(null, (s)-> System.out.println(s) );
    consumeIfPresent.accept("test", (s)-> System.out.println(s));

    BiFunction<Object, Function<Object,Object>,Object> executeIfPresent  = (a,b) ->{
        if(a!=null) {
            return b.apply(a);
        }
        return null;
    };
    executeIfPresent.apply(null, (s)-> {System.out.println(s);return s;} );
    executeIfPresent.apply("test", (s)-> {System.out.println(s);return s;} );

可以在方法调用之前使用拦截器。这就是面向方面编程所关注的。

假设M1(对象测试)是一个方法,M2是一个在方法调用之前应用方面的方法,M2(对象测试2)。如果test2!=null则调用M1,否则执行另一件事。它适用于所有要应用方面的方法。如果要为实例字段和构造函数应用方面,可以使用AspectJ。对于方法方面,Spring也是最佳选择。

对于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();

如果您使用的是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");