Java泛型。孩子延伸父母

时间:2020-01-22 13:55:33

标签: java generics vaadin java-5

您能帮我提供仿制药吗? 我有一个UI表单的要求,但是基于类型,表单会完全更改。我为每种类型的表单创建了具有公共字段和子DTO的Parent DTO。使用vaadin进行验证。我该如何工作。 childdto上的绑定方法给出错误。

ChildlDTO类型未定义getTitle(capture#10-of? ParentDTO)在这里适用

类型中的方法writeBean(capture#10-of?扩展ParentDTO) 活页夹不适用于 参数(ParentDTO)

private ParentDTO dto= new ChildDTO();
private Binder<? extends ParentDTO> binder = new Binder<>(ParentDTO.class);

    binder.forField(type).asRequired("Please select type")
        .bind(ParentDTO::getType, ParentDTO::setType);

在下面为绑定和写入方法编译错误

    binder.forField(title).asRequired("Please select Title")
    .bind(ChildDTO::getTitle, ChildDTO::setTitle);

    binder.writeBean(control);

父类和子类

public abstract class ParentDTO
public class ChildDTO extends ParentDTO {

Vaadin粘合剂

public class Binder<BEAN> implements Serializable {

绑定和写入方法

Binding<BEAN, TARGET> bind(ValueProvider<BEAN, TARGET> getter,
        Setter<BEAN, TARGET> setter);
public void writeBean(BEAN bean) throws ValidationException {

1 个答案:

答案 0 :(得分:1)

只需使用Binder<ParentDTO>,您还可以为其编写扩展类。

但是,您将无法做到这一点

binder.forField(title).asRequired("Please select Title")
    .bind(ChildDTO::getTitle, ChildDTO::setTitle);

因为不能保证传递给它的是ChildDTO

如果需要该方法,则可以执行以下操作,并为每种类型的DTO创建一个函数:

public Binder<ChildDTO> createChildBinder(ChildDTO bean) {
    Binder<ChildDTO> binder = createBinder(bean);
    TextField titleField = new TextField();
    add(titleField);
    binder.forField(titleField).asRequired()
            .bind(ChildDTO::getTitle, ChildDTO::setTitle);
    binder.readBean(bean);
    return binder;
}

public Binder<ChildTwoDTO> createChildBinder(ChildTwoDTO bean) {
    Binder<ChildTwoDTO> binder = createBinder(bean);
    TextField languageField = new TextField();
    add(languageField);
    binder.forField(languageField).asRequired()
            .bind(ChildTwoDTO::getLanguage, ChildTwoDTO::setLanguage);
    binder.readBean(bean);
    return binder;
}

public <T extends ParentDTO> Binder<T> createBinder(T bean) {
    Binder<T> binder = new Binder<>();
    binder.forField(typeField).asRequired("Better fill this...")
            .bind(ParentDTO::getType, ParentDTO::setType);
    return binder;
}

Full code