如何使用 Optional 检查 java 8 中的空值?
How to use Optional to check null values in java 8?
我有一个包含嵌套和内部 class 的 class。在某些程序中,我以传统 java 方式使用等于运算符检查对象的空值。以下是我的代码片段:
class Outer {
Nested nested;
Nested getNested() {
return nested;
}
}
class Nested {
Inner inner;
Inner getInner() {
return inner;
}
}
class Inner {
String foo;
String getFoo() {
return foo;
}
}
下面是我如何对引用变量进行空值检查:
Outer outer = new Outer();
if (outer != null && outer.nested != null && outer.nested.inner != null) {
System.out.println(outer.nested.inner.foo);
}
我知道这也可以使用 java 8 的可选 class 来完成,但我没有找到在特定情况下执行相同操作的方法。
有什么建议吗?
以下代码对我来说效果很好:
Optional.of(new Outer())
.map(Outer::getNested)
.map(Nested::getInner)
.map(Inner::getFoo)
.ifPresent(System.out::println);
强烈建议您观看最近的 Devoxx Belgium presentation "Optional - The Mother of All Bikesheds" by Stuart Marks。 Stuart 正在描述使用它的最初意图、最佳实践和不良实践。
特别是在字段中使用 Optional,引用演示幻灯片:
- Why Not Use Optional in Fields?
- More a style issue than a correctness issue
- use of Optional in fields often arises from slavish desire to eliminate nullable fields.
- remember, eliminating nulls isn't a goal of Optional
- Using Optional in fields..
- creates another object for every field
- introduces a dependent load from memory on every field read
- clutters up your code
- to what benefit? ability to chain methods?
特别是你的例子:
- 为什么
outer != null
检查?它刚刚创建!
- 如果
Nested
实例需要成为 Outer
的一部分并且 Inner
成为 Nested
的一部分让它们成为构造函数的一部分并用一些 @NotNull
来保护代码或以编程方式检查。
我有一个包含嵌套和内部 class 的 class。在某些程序中,我以传统 java 方式使用等于运算符检查对象的空值。以下是我的代码片段:
class Outer {
Nested nested;
Nested getNested() {
return nested;
}
}
class Nested {
Inner inner;
Inner getInner() {
return inner;
}
}
class Inner {
String foo;
String getFoo() {
return foo;
}
}
下面是我如何对引用变量进行空值检查:
Outer outer = new Outer();
if (outer != null && outer.nested != null && outer.nested.inner != null) {
System.out.println(outer.nested.inner.foo);
}
我知道这也可以使用 java 8 的可选 class 来完成,但我没有找到在特定情况下执行相同操作的方法。 有什么建议吗?
以下代码对我来说效果很好:
Optional.of(new Outer())
.map(Outer::getNested)
.map(Nested::getInner)
.map(Inner::getFoo)
.ifPresent(System.out::println);
强烈建议您观看最近的 Devoxx Belgium presentation "Optional - The Mother of All Bikesheds" by Stuart Marks。 Stuart 正在描述使用它的最初意图、最佳实践和不良实践。
特别是在字段中使用 Optional,引用演示幻灯片:
- Why Not Use Optional in Fields?
- More a style issue than a correctness issue
- use of Optional in fields often arises from slavish desire to eliminate nullable fields.
- remember, eliminating nulls isn't a goal of Optional
- Using Optional in fields..
- creates another object for every field
- introduces a dependent load from memory on every field read
- clutters up your code
- to what benefit? ability to chain methods?
特别是你的例子:
- 为什么
outer != null
检查?它刚刚创建! - 如果
Nested
实例需要成为Outer
的一部分并且Inner
成为Nested
的一部分让它们成为构造函数的一部分并用一些@NotNull
来保护代码或以编程方式检查。