Java在通配符上限映射中保留通用类型

时间:2018-10-15 21:12:43

标签: java generics wildcard pecs

从这些类开始

public class Event {

   private EventType eventType;

   public EventType getEventType() {
       return eventType;
   }

   public void setEventType(EventType eventType) {
       this.eventType = eventType;
   }
}

public class OneEvent extends Event {

   public OneEvent() {
       setEventType(EventType.ONE);
   }
}


public interface EventProcessor<T extends Event> {

   Stream<? extends Event> process(T element);

   EventType getType();

}

public enum EventType {
    ONE, TWO
}

我已经创建了实现它的OneEventProcessor和TwoEventProcessor。

public class OneEventProcessor implements EventProcessor<OneEvent> {

@Override
public Stream<? extends Event> process(OneEvent element) {
    return null;
}

@Override
public EventType getType() {
    return EventType.ONE;
}

}

在另一个类中,我想将它们添加到地图类型->处理器中,然后检索并使用。

Map<EventType, EventProcessor<? extends Event>> map = new HashMap<>();
OneEventProcessor oep = new OneEventProcessor();
map.put(oep.getType(), oep);

public Stream<? extends Event> process(Event event) {
    return map.get(event.getEventType()).process(event);
}

这不起作用,因为地图将检索EventProcessor <?扩展Event>,期望捕获<?在处理方法中扩展Event>。

有什么办法可以解决这个问题?

1 个答案:

答案 0 :(得分:0)

只需更改代码即可实现。

  1. OneEvent参数化的OneEventProcessor用于:

    class OneEventProcessor implements EventProcessor<OneEvent> {
    
         @Override
         public Stream<OneEvent> process(OneEvent element) {
             return null;
         }
    
         @Override
         public EventType getType() {
             return EventType.ONE;
         }
     }
    
  2. 使用T参数EventProcessor正确使用:

    interface EventProcessor<T extends Event> {
    
        Stream<T> process(T element);
    
        EventType getType();
    }
    
  3. 为您的process()方法添加适当的类型边界(为简便起见,我在该方法的主体中包括了地图初始化):

    public <T extends Event> Stream<T> process(T event) {
        Map<EventType, EventProcessor<T>> map = new HashMap<>();
        EventProcessor oep = new OneEventProcessor();
        map.put(oep.getType(), oep);
        return map.get(event.getEventType()).process(event);
    }