Java:避免在嵌套类中检查空值(深度空值检查) [英] Java: avoid checking for null in nested classes (Deep Null checking)
问题描述
想象一下,我有一个家庭班级.它包含一个人员列表.每个(类)Person 包含一个(类)地址.每个(类)地址都包含一个(类)邮政编码.任何中间"类可以为空.
Imagine I have a class Family. It contains a List of Person. Each (class) Person contains a (class) Address. Each (class) Address contains a (class) PostalCode. Any "intermediate" class can be null.
那么,有没有一种简单的方法可以访问 PostalCode,而不必在每一步都检查 null?即,有没有办法避免以下菊花链代码?我知道没有本地"Java 解决方案,但希望有人知道图书馆或其他东西.(检查 Commons & Guava 并没有看到任何东西)
So, is there a simple way to get to PostalCode without having to check for null in every step? i.e., is there a way to avoid the following daisy chaining code? I know there's not "native" Java solution, but was hoping if anyone knows of a library or something. (checked Commons & Guava and didn't see anything)
if(family != null) {
if(family.getPeople() != null) {
if(family.people.get(0) != null) {
if(people.get(0).getAddress() != null) {
if(people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
}
}
}
}
不,不能改变结构.它来自我无法控制的服务.
No, can't change the structure. It's from a service I don't have control over.
不,我不能使用 Groovy,它很方便,Elvis";操作员.
No, I can't use Groovy and it's handy "Elvis" operator.
不,我不想等待 Java 8 :D
No, I'd prefer not to wait for Java 8 :D
我不敢相信我是有史以来第一个厌倦编写这样的代码的开发人员,但我一直找不到解决方案.
I can't believe I'm the first dev ever to get sick 'n tired of writing code like this, but I haven't been able to find a solution.
推荐答案
您可以用于:
product.getLatestVersion().getProductData().getTradeItem().getInformationProviderOfTradeItem().getGln();
可选等价物:
Optional.ofNullable(product).map(
Product::getLatestVersion
).map(
ProductVersion::getProductData
).map(
ProductData::getTradeItem
).map(
TradeItemType::getInformationProviderOfTradeItem
).map(
PartyInRoleType::getGln
).orElse(null);
这篇关于Java:避免在嵌套类中检查空值(深度空值检查)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!