【问题标题】:Generic object with builder pattern具有构建器模式的通用对象
【发布时间】:2020-01-26 14:45:50
【问题描述】:

我的班级中有一个Producer<?, ?> producer 字段,该字段的实现取决于使用构建器模式的给定状态,例如:

private void changeImplementation(int state) {
    switch (state) {
        case 0:
            producer = builder
                           .setKey(Long.class)
                           .setValue(String.class)
                           .setOtherStuff(...)
                           .build() // return the object with correct key and value
        break;
        case 1:
            ...
}

但每当我在生产者上调用方法时(例如使用类型 Producer<Long, String>),都会给出此错误(Eclipse EE):

The method method(Record<capture#9-of ?,capture#10-of ?>) in the type Producer<capture#9-of ?,capture#10-of ?> is not applicable for the arguments (Record<Long,String>)

build() 之前或在方法调用内部进行强制转换没有帮助。该构建模式在项目的其他地方完美运行。

【问题讨论】:

    标签: java eclipse generics design-patterns casting


    【解决方案1】:

    问题与构建器模式无关,而是您的producer 字段的类型被未知类型? 调用。出于这个原因,您只能为作为未知类型子类型的Producer 的泛型类型的参数赋值。但是,类型是 ? 子类型的唯一值是 null,因此它确实限制了您可以使用 Producer<?,?> 执行的操作。

    要解决这个问题,您必须以不同的方式绑定通用类型的设计。

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2016-01-17
      • 1970-01-01
      • 2020-03-28
      • 2013-08-27
      • 2013-02-24
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多