<分区>
我有这样一个类结构:
public class Foo {
private FooB fooB;
public Optional<FooB> getFooB() {
return Optional.ofNullable(fooB);
}
}
public class FooB {
private String a;
private String b;
public String getA() {
return a;
}
public String getB() {
return b;
}
}
我想做的是这样的:
main() {
//initialize a Foo object called foo
String a = foo.getFooB().ifPresent(FooB::getA);
}
基本上,如果 foo 对象返回 FooB,则从 FooB
中获取字段 String a
并将其存储在局部变量 String a
中.我怎样才能在一行中优雅地做到这一点?