Java泛型捕获不能应用于使用Factory模式扩展

时间:2018-02-27 19:13:58

标签: java generics interface factory

我有一个抽象的LogEvent类,我有该类的Partitioner接口。所以X extends LogEventY implements Partitioner<X>我将这个映射存储在一个对象中,这样我就可以通过简单的查找在运行时获得适当的分区器类。我只写相关部分。

分区程序仅适用于LogEvent

public interface Partitioner<T extends LogEvent> {
    List<Partition> getPartitions(T event);

它分区X类型的LogEvents

public class XPartitioner implements Partitioner<X> 

这包含映射,它也有一个默认值,此处未显示。

public class PartitionerFactory {
    public PartitionerFactory register(Class<? extends LogEvent> clazz, Partitioner<? extends LogEvent> partitioner) {
        partitionerMap.put(clazz, partitioner);

注册作品

PartitionerFactory partitionerFactory = // ...
Partitioner<? extends LogEvent> partitioner = new XPartitioner();
partitionerFactory.register(X.class, partitioner);

然而,这会产生错误

LogEvent event = // Fetched from somewhere
Partitioner<? extends LogEvent> partitioner = partitionerFactory.get(event.getClass());
List<Partition> partitions = partitioner.getPartitions(event);

此操作失败,出现以下错误:

capture<? extends LogEvent> in Partitioner cannot be applied to LogEvent

如果我更改了寄存器并且Partitioner<LogEvent>获得了工作,但现在注册失败的原因相同。我缺少什么&amp;做错了?

修改:我添加了以下内容,它适用于注册并获取:

<T extends LogEvent> List<Partition> getPartitions(T event);

但是,现在我的XPartitioner需要实现这个功能:

public <T extends LogEvent> List<Partition> getPartitions(T event)

我真的很困惑。

编辑2: 如果我将签名更改为以下内容,它会起作用,它会发出“未选中分配”的警告,因为基础对象是Partitioner<LogEvent>

public PartitionerFactory register(Class<? extends LogEvent> clazz, Partitioner partitioner) {

0 个答案:

没有答案