How to avoid null checking in Java?

后端 未结 30 3269
失恋的感觉
失恋的感觉 2020-11-21 04:43

I use object != null a lot to avoid NullPointerException.

Is there a good alternative to this?

For example I often use:



        
30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 05:36

    Probably the best alternative for Java 8 or newer is to use the Optional class.

    Optional stringToUse = Optional.of("optional is there");
    stringToUse.ifPresent(System.out::println);
    

    This is especially handy for long chains of possible null values. Example:

    Optional i = Optional.ofNullable(wsObject.getFoo())
        .map(f -> f.getBar())
        .map(b -> b.getBaz())
        .map(b -> b.getInt());
    

    Example on how to throw exception on null:

    Optional optionalCarNull = Optional.ofNullable(someNull);
    optionalCarNull.orElseThrow(IllegalStateException::new);
    

    Java 7 introduced the Objects.requireNonNull method which can be handy when something should be checked for non-nullness. Example:

    String lowerVal = Objects.requireNonNull(someVar, "input cannot be null or empty").toLowerCase();
    

提交回复
热议问题