【问题标题】:Java Generics. Child extends ParentJava 泛型。子扩展父
【发布时间】:2020-01-23 15:18:13
【问题描述】:

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

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

类型中的方法 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 {

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 {

还有

【问题讨论】:

  • 这个:Binder&lt;? extends ParentDTO&gt; binder 必须是 Binder&lt;ChildDTO&gt; = new Binder&lt;&gt;(ChildDTO.class)
  • getTitle 仅在其中一个子对象中,而不在 parentdto 中。我无法将 Binder 定义创建为 Binder,因为我也可以拥有其他子对象 Binder
  • 我可能会摆脱 binder.forField(type).asRequired("请选择类型") .bind(ParentDTO::getType, ParentDTO::setType);通过使用 childDTO 而不是孩子可以访问父母而不是其他方式
  • 当您清楚地使用 java 8 构造时,为什么要使用 java-5 标记您的问题?
  • 泛型来自 Java 5

标签: java generics vaadin java-5


【解决方案1】:

只需使用Binder&lt;ParentDTO&gt;,然后您还可以为其编写扩展类。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    相关资源
    最近更新 更多