还用 != null 判空?新姿势,值得学习!
码农突围
共 6881字,需浏览 14分钟
·
2022-07-31 14:09
来源:blog.csdn.net/zjhred/article/details/84976734
引言
在文章的开头,先说下NPE问题,NPE问题就是,我们在开发中经常碰到的NullPointerException.假设我们有两个类,他们的UML类图如下图所示
在这种情况下,有如下代码:
user.getAddress().getProvince();
这种写法,在user为null时,是有可能报NullPointerException异常的。为了解决这个问题,于是采用下面的写法:
if(user!=null){
Address address = user.getAddress();
if(address!=null){
String province = address.getProvince();
}
}
这种写法是比较丑陋的,为了避免上述丑陋的写法,让丑陋的设计变得优雅。JAVA8提供了Optional类来优化这种写法,接下来的正文部分进行详细说明
API介绍
1、Optional(T value),empty(),of(T value),ofNullable(T value)
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
public final class Optional<T> {
//省略....
private static final Optional<?> EMPTY = new Optional<>();
private Optional() {
this.value = null;
}
//省略...
public static<T> Optional<T> empty() {
"unchecked") (
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
}
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
2、orElse(T other),orElseGet(Supplier<? extends T> other)和orElseThrow(Supplier<? extends X> exceptionSupplier)
public void test() {
User user = null;
user = Optional.ofNullable(user).orElse(createUser());
user = Optional.ofNullable(user).orElseGet(() -> createUser());
}
public User createUser(){
User user = new User();
user.setName("zhangsan");
return user;
}
User user = null;
Optional.ofNullable(user).orElseThrow(()->new Exception("用户不存在"));
3、map(Function<? super T, ? extends U> mapper)和flatMap(Function<? super T, Optional> mapper)
public final class Optional<T> {
//省略....
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}
//省略...
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value));
}
}
}
public class User {
private String name;
public String getName() {
return name;
}
}
String city = Optional.ofNullable(user).map(u-> u.getName()).get();
public class User {
private String name;
public Optional<String> getName() {
return Optional.ofNullable(name);
}
}
String city = Optional.ofNullable(user).flatMap(u-> u.getName()).get();
4、isPresent()和ifPresent(Consumer<? super T> consumer)
public final class Optional<T> {
//省略....
public boolean isPresent() {
return value != null;
}
//省略...
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
}
if (user != null){
// TODO: do something
}
User user = Optional.ofNullable(user);
if (Optional.isPresent()){
// TODO: do something
}
Optional.ofNullable(user).ifPresent(u->{
// TODO: do something
});
5、filter(Predicate<? super T> predicate)
public final class Optional<T> {
//省略....
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
Optional<User> user1 = Optional.ofNullable(user).filter(u -> u.getName().length()<6);
实战使用
例一
public String getCity(User user) throws Exception{
if(user!=null){
if(user.getAddress()!=null){
Address address = user.getAddress();
if(address.getCity()!=null){
return address.getCity();
}
}
}
throw new Excpetion("取值错误");
}
public String getCity(User user) throws Exception{
return Optional.ofNullable(user)
.map(u-> u.getAddress())
.map(a->a.getCity())
.orElseThrow(()->new Exception("取指错误"));
}
例二
if(user!=null){
dosomething(user);
}
Optional.ofNullable(user)
.ifPresent(u->{
dosomething(u);
});
例三
public User getUser(User user) throws Exception{
if(user!=null){
String name = user.getName();
if("zhangsan".equals(name)){
return user;
}
}else{
user = new User();
user.setName("zhangsan");
return user;
}
}
public User getUser(User user) {
return Optional.ofNullable(user)
.filter(u->"zhangsan".equals(u.getName()))
.orElseGet(()-> {
User user1 = new User();
user1.setName("zhangsan");
return user1;
});
}
(完)
码农突围资料链接
1、卧槽!字节跳动《算法中文手册》火了,完整版 PDF 开放下载!
2、计算机基础知识总结与操作系统 PDF 下载
3、艾玛,终于来了!《LeetCode Java版题解》.PDF
4、Github 10K+,《LeetCode刷题C/C++版答案》出炉.PDF欢迎添加鱼哥个人微信:smartfish2020,进粉丝群或围观朋友圈。
评论