我的类(class)有 SimpleObjectProperty<SomeFunctionalInterface>
成员。我不想让我的代码因对其值进行任何空检查而变得困惑;相反,我有一个默认实现 SomeFunctionalInterface
,唯一的方法就是空的。目前,我将此默认值指定为属性的初始值,并且在该属性上还有一个更改监听器,如果有人尝试将其值设置为 null,则该属性的值将设置回默认实现。然而,这感觉有点笨拙,并且从事物的更改监听器内部设置事物的值让我感觉很肮脏。
缺少创建我自己的类来扩展 SimpleObjectProperty
,如果对象属性的当前值为null
,是否有任何方法可以让对象属性返回一些预定义的默认值? ?
最佳答案
您可以公开对属性的非空绑定(bind):
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);
}
// ...
}
这并不适用于所有用例,但可能足以满足您的需要。
关于java - 在 JavaFX SimpleObjectProperty 中禁止 null(或返回默认值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45971740/