I want to declare that a Generic Type is one of a subset of types, but I'm not sure how. Here is a simplified version of my situation:
Modules communicate with events. There are different types of events. Modules can consume different event types using different methods.
class EventProducerA implements Producer<EventTypeA>{
@Override
public EventTypeA produce_event(){
return new EventTypeA(...);
}
}
class EventProducerB implements Producer<EventTypeB>{
@Override
public EventTypeB produce_event(){
return new EventTypeB(...);
}
}
class EventConsumer{
public void feed_event(EventTypeA ev){
...
}
public void feed_event(EventTypeB ev){
...
}
}
Now, I have a main class where I link these modules. I WANT to have the code:
Producer<EventTypeA OR EventType B> producer = some_flag?new EventProducerA():new EventProducerB();
Consumer consumer = new EventConsumer()
consumer.feed_event(producer.produce_event());
Which would cause a compile error if some EventTypeC which is not handled by the consumer is produced by producer.
But unfortunately there is no OR option for Generic Types in Java.
So what's the best thing to do? Am I forced to use ugly casting solutions?