2017-08-31 77 views
1

我有一個SimpleObjectProperty<SomeFunctionalInterface>成員的類。我不想混淆我的代碼,對它的值進行任何空的檢查;相反,我有一個默認實現SomeFunctionalInterface,它的唯一方法是簡單的空。目前,我將此默認值指定爲屬性的初始值,並且還有一個屬性更改偵聽器,如果任何人嘗試將其值設置爲null,則將屬性值設置爲默認實現。但是,這感覺有點笨拙,並且從其變化監聽者內部設置一個事物的價值使我感到骯髒。在JavaFX中禁止null(或返回默認值)SimpleObjectProperty

創建我自己的類擴展SimpleObjectProperty的缺點,有沒有什麼辦法讓對象屬性返回一些預定義的默認值,如果它的當前值是null

回答

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); 
    } 

    // ... 
} 

這將不適合所有情況的工作,但可能足以滿足您的需要。