我有一个SimpleObjectProperty<SomeFunctionalInterface>
成员的班级。我不希望我的代码与其值的任何空值检查混乱;相反,我有一个SomeFunctionalInterface
的默认实现,其中唯一的方法是空的。目前,我将此默认值指定为属性的初始值,并且还在属性上具有更改侦听器,如果有人尝试将其值设置为null,则会将该属性的值设置回默认实现。然而,这感觉有点笨拙,从变化听众中设置一个东西的价值让我觉得很脏。
如果没有创建我自己的扩展SimpleObjectProperty
的类,有没有办法让对象属性返回一些预定义的默认值,如果它的当前值为null
?
答案 0 :(得分:2)
您可以向属性公开非空绑定:
public class SomeBean {
private final ObjectProperty<SomeFunctionalInterface> value = new SimpleObjectProperty<>();
private final SomeFunctionalInterface defaultValue = () -> {} ;
private final Binding<SomeFunctionalInterface> nonNullBinding = Bindings.createObjectBinding(() -> {
SomeFunctionalInterface val = value.get();
return val == null ? defaultValue : val ;
}, property);
public final Binding<SomeFunctionalInterface> valueProperty() {
return nonNullBinding ;
}
public final SomeFunctionalInterface getValue() {
return valueProperty().getValue();
}
public final void setValue(SomeFunctionalInterface value) {
valueProperty.set(value);
}
// ...
}
这不适用于所有用例,但可能足以满足您的需求。