开发手册 欢迎您!
软件开发者资料库

Java 检查判断变量null(空值)的方法示例代码

本文主要介绍Java中,调用方法前判断检测,变量是否为null(空值)的方法及示例代码。

1、一般方法判断null值

if(country != null && country.getCity() != null && country.getCity().getSchool() != null && country.getCity().getSchool().getStudent() != null .....) {    isValid = true;}

2、通过Optional判断null值

if (Optional.ofNullable(country)            .map(Country::getCity)            .map(City::getSchool)            .map(School::getStudent)            .isPresent()) {    isValid = true;}

boolean isValid = Optional.ofNullable(country)                          .map(Country::getCity)                          .map(City::getSchool)                          .map(School::getStudent)                          .isPresent();

boolean isValid = Optional.ofNullable(country)    .map(country -> country.getCity()) //Or use method reference Country::getCity    .map(city -> city.getSchool())    .map(school -> school.getStudent())    .map(student -> true)    .orElse(false);

3、使用Supplier var-args参数判断null值

 boolean isValid = isValid(() -> address, // first level                              () -> address.getCity(),   // second level                              () -> address.getCountry(),// second level                              () -> address.getStreet(), // second level                              () -> address.getZip(),    // second level                              () -> address.getCountry() // third level                                           .getISO()@SafeVarargspublic static boolean isValid(Supplier... suppliers) {    for (Supplier supplier : suppliers) {        if (Objects.isNull(supplier.get())) {            // log, handle specific thing if required            return false;        }    }    return true;}

boolean isValid = isValid(  Arrays.asList("address", "city", "country",                                          "street", "zip", "Country ISO"),                            () -> address, // first level                            () -> address.getCity(),   // second level                            () -> address.getCountry(),// second level                            () -> address.getStreet(), // second level                            () -> address.getZip(),    // second level                            () -> address.getCountry() // third level                                         .getISO()                         );@SafeVarargspublic static boolean isValid(List fieldNames, Supplier... suppliers) {    if (fieldNames.size() != suppliers.length){         throw new IllegalArgumentException("...");    }    for (int i = 0; i < suppliers.length; i++) {        if (Objects.isNull(suppliers.get(i).get())) {            LOGGER.info( fieldNames.get(i) + " is null");            return false;        }    }    return true;}

2009-2024 Copyright Wonhero.Com All Rights Reserved
深圳幻海软件技术有限公司 版权所有