所以我想对值中包含的值进行空安全检查。
所以我有 3 个对象包含在彼此中:
Person 有一个 clothes object 有一个 country object 有一个 capital
所以一个人可能没有衣服,所以像这样的检查会抛出一个空指针:
if (person.getClothes.getCountry.getCapital)
如果路径上的任何对象为空,我将如何做出这样的声明只返回 false?
我也不想这样做。 (如果可能的话,使用 Java-8 中的单行代码。
if (person !=null) {
if (person.getClothes != null) {
if (person.getClothes.getCountry !=null) {
etc....
}
}
}
原文由 Blawless 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以通过
Optional::map
链接所有这些调用。我觉得这比if/else
更容易阅读,但它可能只是我