我的课程中有一个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()之前或方法调用内部进行强制转换没有帮助。构建模式可以在项目中的其他地方完美地工作。

最佳答案

该问题与构建器模式无关,而是与producer字段的类型以未知类型?调用。因此,只能将值分配给Producer泛型类型的参数,这些类型是未知类型的子类型。但是,类型为?子类型的唯一值是null,因此它实际上限制了您可以对Producer<?,?>进行的操作。

为了解决这个问题,您必须以不同的方式约束您的通用设计类型。

10-07 12:52