繁体   English   中英

Java泛型。 子扩展父

[英]Java Generics. Child extends Parent

你能帮我做一个泛型吗? 我有一个要求,我有一个 UI 表单,但根据类型,表单会完全改变。 我已经为每种类型的表单创建了带有公共字段和子 DTO 的父 DTO。 使用 vaadin 进行验证。 我如何让这个工作。 childdto 上的绑定方法给出错误。

ChildlDTO 类型未定义适用于此处的 getTitle(capture#10-of ? extends ParentDTO)

类型 Binder 中的方法 writeBean(capture#10-of ? extends 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 {

瓦丁粘合剂

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 {

只需使用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;
}

完整代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM