我正在使用 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 实例化它们。
如何修复上述错误?
最佳答案
在尝试了 @Rogue 在评论中给我的提示后,我首先尝试使用 Set<>,但最终实现的技巧是向上进行另一个抽象级别,并在类中使用 Collection<> 而不是 HashSet<>定义(Oracle Docs)。
public class AnotherClass implements Serializable {
@NotNull
private int id = -1;
private Collection<MyClass> myHashSet= new HashSet<MyClass>();
}
关于java - 无法将 java.util.Collections$EmptySet 转换为 java.util.HashSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61060007/