2017-08-31 6 views
1

私はSimpleObjectProperty<SomeFunctionalInterface>メンバのクラスを持っています。私はその値のヌルチェックでコードを乱雑にしたくありません。代わりに私はSomeFunctionalInterfaceのデフォルトの実装を持っています。その唯一のメソッドは単に空です。現在のところ、このデフォルト値をプロパティの初期値として割り当て、変更リスナーをプロパティに設定して、誰かがその値をnullに設定しようとすると、プロパティの値をデフォルトの実装に戻します。しかし、これはちょっとぎこちない感じで、変更リスナーの中から値を設定すると、気分が悪くなります。JavaFX SimpleObjectPropertyでnull(またはデフォルト値を返す)を禁止します

SimpleObjectPropertyを拡張して自分のクラスを作成するのではなく、現在の値がnullの場合、オブジェクトのプロパティを取得して定義済みのデフォルト値を返す方法はありますか?

答えて

2

あなたは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); 
    } 

    // ... 
} 

これは、すべてのユースケースでは動作しませんが、あなたが必要なもののために十分です。

関連する問題