String s = foo.getBar().getFrobz().getNobz().getBaz();
我想返回 getBaz()
的值。问题是,任何其他方法都可能返回 null
- 在这种情况下,我只想返回一个空字符串。
这是实现这种效果的一种方法:
String s = "";
if (foo.getBar() != null ) {
if (foo.getBar().getFrobz() != null) {
if (foo.getBar().getFrobz().getNobz() != null) {
if (foo.getBar().getFrobz().getNobz().getBaz() != null) {
s = foo.getBar().getFrobz().getNobz().getBaz();
}
}
}
}
还有一个更简单的方法:
String s = "";
try {
s = foo.getBar().getFrobz().getNobz().getBaz();
} catch (NullPointerException npe) {
}
我听说异常比 if 语句更昂贵,但它们看起来确实更简洁。也许这个问题可以用另一种方式解决?感谢您的帮助。
最佳答案
如何使用 Optional
类?它是为这种情况而创建的。你可以像这样使用它:
return Optional.ofNullable(foo.getBar());
if(optional.isPresent()) {
// do something with the value
}
请注意,这仅适用于 Java 8。除此之外,强烈建议不要使用值 null
。如果 null
值有问题,您最好使用 Exception
。
请注意,foo.getBar().getFrobz().getNobz().getBaz()
在干净代码方面被称为“火车残骸”。您应该避免像这样暴露对象的内部结构。
以下程序将打印“不存在”:
public class Main {
public static void main(String[] args) {
Foo foo = new Foo();
final Optional<String> s = foo.getBar()
.flatMap(Bar::getFrobz)
.flatMap(Frobz::getNobz)
.flatMap(Nobz::getBaz);
if(s.isPresent()) {
System.out.println("present");
} else {
System.out.println("not present");
}
}
private static class Foo {
Bar bar;
public Optional<Bar> getBar() {
return ofNullable(bar);
}
}
private static class Bar {
Frobz frobz;
public Optional<Frobz> getFrobz() {
return ofNullable(frobz);
}
}
private static class Frobz {
Nobz nobz;
public Optional<Nobz> getNobz() {
return ofNullable(nobz);
}
}
private static class Nobz {
String baz;
public Optional<String> getBaz() {
return ofNullable(baz);
}
}
}
还有 null object pattern这在这种情况下会很方便。
关于java - 使用 if 语句检查空值与异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36296987/