How to avoid null checking in Java?

后端 未结 30 3291
失恋的感觉
失恋的感觉 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:21

    Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections

    Example:

    String foo;
    ...
    if( StringUtils.isBlank( foo ) ) {
       ///do something
    }
    

    or (depending on what you need to check):

    String foo;
    ...
    if( StringUtils.isEmpty( foo ) ) {
       ///do something
    }
    

    The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.

    Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)

    public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
        Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
        return read(new StringReader(xml), true, validationEventHandler);
    }
    

    And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)

    Example on how to use this static classf from spring(org.springframework.util.Assert)

    Assert.notNull(validationEventHandler,"ValidationHandler not Injected");
    

提交回复
热议问题