方法一:.对有可能存在的数值和不存在的数值提前判空:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14String isocode = user.getAddress().getCountry().getIsocode().toUpperCase(); if (user != null) { Address address = user.getAddress(); if (address != null) { Country country = address.getCountry(); if (country != null) { String isocode = country.getIsocode(); if (isocode != null) { isocode = isocode.toUpperCase(); } } } }
解决办法:
1.字段提前判空
复制代码
1
2
3//使用StringUtils.isNotBlank StringUtils.isNotBlank(catalogNo)
2.检测字段为空,并给默认数值
复制代码
1
2Objects.requireNonNullElse(pmsUser.getUserName(), "")
3.三目运算符
复制代码
1
2
3// 返回兜底的空字符串 String name = channelDao.getOne() == null ? "" : channelDao.getOne().getName();
4.使用Optional函数
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27//如果将 null 当作参数传进去 of() 会报空指针异常 Optional<User> opt = Optional.of(user); //当对象可能存在或者不存在,应该使用 ofNullable()。 Optional<User> opt = Optional.ofNullable(user); //获取数值使用get方法 opt.getName(); //数值和对象如果可能提前为空的情况下可以使用isPresent 进行提前判断 User user = new User("zhangsan", "18"); Optional<User> opt = Optional.ofNullable(user); assertTrue(opt.isPresent()); assertEquals(user.getEmail(), opt.get().getEmail()); /** 导入包:import static org.junit.Assert.*;//必须是static assertEquals 和 assertTrue 区别 相同之处:都能判断两个值是否相等 assertTrue 如果为true,则运行success,反之Failure assertEquals 如果预期值与真实值相等,则运行success,反之Failure 不同之处: assertEquals 运行Failure会有错误提示,提示预期值是xxx,而实际值是xxx。容易调式 assertTrue 没有错误提示 **/ //Optional 类提供了 API 用以返回对象值,或者在对象为空的时候返回默认值 User user = null; User user2 = new User("zhangsan", "22"); //此时 user 对象为 null,result 返回 orElse() 参数 user2,如果对象初始值不是 null,那么默认值会被忽略。 User result = Optional.ofNullable(user).orElse(user2);
转换与过滤
通过 map() 和 flatMap() 方法可以转换 Optional 的值。
复制代码
1
2
3
4
5User user = new User("zhangsan.com", "777"); String email = Optional.ofNullable(user) .map(u -> u.getEmail()).orElse("111@gmail.com"); assertEquals(email, user.getEmail());
map() 对值应用(调用)作为参数的函数,然后将返回的值包装在 Optional 中。这就使对返回值进行链式调用的操作成为可能 —— 这里的下一环就是 orElse() 。
flatMap() 也需要函数作为参数,并对值调用这个函数,然后直接返回结果
除了转换值之外,Optional 类也提供了按条件“过滤”值的方法。
filter() 接受一个 Predicate 参数,返回测试结果为 true 的值。如果测试结果为 false,会返回一个空的 Optional。
复制代码
1
2
3
4
5User user = new User("zhangsan.com", "777"); Optional<User> result = Optional.ofNullable(user) .filter(u -> u.getEmail() != null && u.getEmail().contains("@")); assertTrue(result.isPresent());
参考更多Optional 方法
最后
以上就是知性猎豹最近收集整理的关于NPE的总结示例的全部内容,更多相关NPE内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复