对象判空
项目中经常遇到对象判空,如果是对象成员变量逐层判断, 会写很多if else 的逻辑语句
public String testSimple(Context c) {
if (c == null) {
return "";
}
if (c.getUser() == null) {
return "";
}
if (c.getUser().getCity() == null) {
return "";
}
if (c.getUser().getCity().getInfo() == null) {
return "";
}
return c.getUser().getCity() .getInfo();
}
java 8 中 Optional
获取对象中某个成员变量
public String testOptional(Context c) {
return Optional.ofNullable(c).flatMap(c::getUser())
.flatMap(user::getCity())
.map(city::getInfo)
.orElse("");
}
实践
UserDto userDto = userClientService.selectUser(userId);
Long orgId = Optional.ofNullable(userDto).map(item -> item.getOrgId()).orElse(0L);
if (orgId > 0) {
//对象不为空,业务逻辑
} else {
LOGGER.error(null, "无法获取用户的组织机构Id,userId:{},key:{}", userId, ossKey);
}