java8使用Optional实现优美的npe判断
作者:互联网
代码示例
import java.util.Optional;
public class test02 {
public static void main(String[] args) {
System.out.println("方法1输出的结果是:" + getName());
System.out.println("方法2输出的结果是:" + getUser());
}
public static String getName() {
User user = new User("hua wei",22);
if (user != null) {
String name = user.getName();
if (name != null) {
return name.toUpperCase();
} else {
return null;
}
} else {
return null;
}
}
public static String getUser() {
User user = new User("tao bao",22);
Optional<User> userOptional = Optional.ofNullable(user);
return userOptional.map(User::getName)
.map(String::toUpperCase)
.orElse(null);
}
}
#输出的结果是:
方法1输出的结果是:HUA WEI
方法2输出的结果是:TAO BAO
标签:return,String,npe,getName,User,null,Optional,java8,user 来源: https://blog.csdn.net/Natsu_xia/article/details/116237706