Bla*_*ess 6 java null if-statement optional java-8
所以我想对值中包含的值进行空值安全检查.
所以我有3个对象包含在彼此之内:
人具有衣服对象,其具有具有资本的国家对象
所以一个人可能没有衣服,所以像这样的支票会抛出一个空指针:
if (person.getClothes.getCountry.getCapital)
Run Code Online (Sandbox Code Playgroud)
如果路径上的任何对象为空,我将如何创建这样的语句只返回false?
我也不想这样做.(如果可能的话,在Java-8中使用单行程序.
if (person !=null) {
if (person.getClothes != null) {
if (person.getClothes.getCountry !=null) {
etc....
}
}
}
Run Code Online (Sandbox Code Playgroud)
Eug*_*ene 10
您可以通过链接所有这些电话Optional::map.我发现这比阅读更容易if/else,但可能只是我
Optional.ofNullable(person.getClothes())
.map(Clothes::getCountry)
.map(Country::getCapital)
.ifPresent(...)
Run Code Online (Sandbox Code Playgroud)
这些“级联”空检查确实是偏执和防御性编程。我首先要问一个问题,让它快速失败或在将输入存储到这样的数据结构之前验证输入不是更好吗?
现在回答问题。由于您已经使用了嵌套的空检查,您可以使用Optional<T>和 方法进行类似的操作Optional::map,该方法可以让您获得更好的控制:
Optional.ofNullable(person.getClothes())
.map(clothes -> clothes.getCountry())
.map(country -> country.getCapital())
.orElse(..) // or throw an exception.. or use ifPresent(...)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5445 次 |
| 最近记录: |