0

我正在使用 Vaadin14 和 Java 1.8。我想实现一个多选组合框,这就是我使用以下 Vaadin 插件的原因:https ://vaadin.com/directory/component/multiselect-combo-box/api/org/vaadin/gatanaso/MultiselectComboBox.html

实例化和使用组合框效果很好,但我得到了错误

java.lang.RuntimeException: java.lang.ClassCastException: Cannot cast java.util.Collections$EmptySet to java.util.HashSet

当试图“保存”一个没有在组合框中选择任何项目的对象时。如果我至少选择了一个项目,它可以正常工作,但是一旦选择为空并且我尝试保存对象(“AnotherClass”),我就会收到错误消息。

// creating a combobox 
private MultiselectComboBox<MyClass> multiselectComboBox;
multiselectComboBox= new MultiselectComboBox<>();   

// setting items to choose from
final MyClassDataProvider dataProvider = new MyClassDataProvider();
List<MyClass> allAvailableOptions = new ArrayList<>(dataProvider.getItems());
multiselectComboBox.setItems(allAvailableOptions);
multiselectComboBox.setItemLabelGenerator(MyClass::getName); // display name only

// binding the combobox to a field of AnotherClass
binder = new BeanValidationBinder<>(AnotherClass.class);
binder.forField(multiselectComboBox)
            .bind("myHashSet");

// save-button
save = new Button("Save");
save.addClickListener(event -> {
    if (currentObject!= null
         && binder.writeBeanIfValid(currentObject)) { // error in this line
         viewLogic.saveRisk(currentObject);
    }
    });

HashSet 是以下类中的一个属性:

public class AnotherClass  implements Serializable {

     @NotNull
     private int id = -1;

     private HashSet<MyClass> myHashSet= new HashSet<MyClass>();

}

当我创建 AnotherClass 的实例时,我总是不使用 null 而是使用属性 myHashSet 的空 HashSet 来实例化它们。

如何解决上述错误?

4

1 回答 1

0

在尝试了@Rogue 在评论中给我的提示之后,我首先使用 Set<> 进行了尝试,但最终的诀窍是向上进行另一个抽象级别并在类定义中使用 Collection<> 而不是 HashSet<> (Oracle文档)。

public class AnotherClass  implements Serializable {

     @NotNull
     private int id = -1;

     private Collection<MyClass> myHashSet= new HashSet<MyClass>();

}
于 2020-04-06T15:15:03.093 回答