所以我想对包含在值中的值进行空安全检查。
所以我有 3 个对象:
Person has a clothes object which has a country object which has a capital
所以一个人可能没有衣服,所以这样的检查会抛出一个空指针:
if (person.getClothes.getCountry.getCapital)
如果路径上的任何对象为 null,我如何使这样的语句只返回 false?
我也不想这样做。 (如果可能,使用 Java-8 中的单行代码。
if (person !=null) {
if (person.getClothes != null) {
if (person.getClothes.getCountry !=null) {
etc....
}
}
}
最佳答案
您可以通过 Optional::map
链接所有这些调用。我觉得这比 if/else
更容易阅读,但可能只有我会这样
Optional.ofNullable(person.getClothes())
.map(Clothes::getCountry)
.map(Country::getCapital)
.ifPresent(...)
关于java - JAVA 8 中的 NULL 安全对象检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52220606/