如何使 JavaFX ListProperty 只能通过自定义方法进行修改

How to make JavaFX ListProperty modifiable only through custom methods

我有一个私人列表,我一般不希望它可以从外部修改。仅当对象有效时才允许从外部添加。所以我以前是这样写的:

private List<Object> list = new ArrayList<>();

public List<Object> getList()
{
    return Collections.unmodifiableList(list);
}

public void addObject(Object object)
{
    if (isObjectValid(object)) //any validation
        list.add(object);
}

现在出于 JavaFX 的目的,我将列表转换为 属性:

private ListProperty<Object> list =
               new SimpleListProperty<>(FXCollections.observableArrayList());

为了从 属性 之类的数据绑定和 ListChangeListener 中获益,我必须向外部世界提供 属性。但是也提供了对列表的所有方法的访问。 (使用 ReadOnlyListProperty 没有任何效果,因为列表实例本身永远不会改变。)我该怎么做才能实现所有目标:

未测试,但请尝试:

private ListProperty<Object> list = new SimpleListProperty<>(FXCollections.observableArrayList());

private ReadOnlyListWrapper<Object> publicList = new ReadOnlyListWrapper<>();

在构造函数中:

publicList.bind(Bindings.createObjectBinding(
    () -> FXCollections.unmodifiableObservableList(list.getValue()),
    list));

那么你的访问方法是

public ReadOnlyListProperty<Object> getList() {
    return publicList.getReadOnlyProperty();
}