在JavaFX中禁止null(或返回默认值)SimpleObjectProperty
问题描述:
我有一个SimpleObjectProperty<SomeFunctionalInterface>
成员的类。我不想混淆我的代码,对它的值进行任何空的检查;相反,我有一个默认实现SomeFunctionalInterface
,它的唯一方法是简单的空。目前,我将此默认值指定为属性的初始值,并且还有一个属性更改侦听器,如果任何人尝试将其值设置为null,则将属性值设置为默认实现。但是,这感觉有点笨拙,并且从其变化监听者内部设置一个事物的价值使我感到肮脏。在JavaFX中禁止null(或返回默认值)SimpleObjectProperty
创建我自己的类扩展SimpleObjectProperty
的缺点,有没有什么办法让对象属性返回一些预定义的默认值,如果它的当前值是null
?
答
您可能使一个非空结合的财产:
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);
}
// ...
}
这将不适合所有情况的工作,但可能足以满足您的需要。