java isnull方法_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()

@SafeVarargs

public 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()

);

@SafeVarargs

public 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;

}


版权声明:本文为weixin_39664962原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。