简体   繁体   中英

Coding Type constraints in Java with Generics

I'm making a system wherein producer-modules produce events, and consumer-modules consume these events. A router-class sends events generated by each producer to its list of consumers. There are different types of events, so both Producer and Consumer classes are parameterized by a generic "EventType".

In my Router code I have a HashMap linking Producers to Consumers. I want to express the constraint that each consumer for a given Producer must consume the same EventType that that Producer produces (but EventType may be different for different Producers in the table).

Currently, in my Router class, I declare my HashMap as:

Map<Producer, List<Consumer>> src_to_consumers;

I'd like to do something like

Map<Producer<EventType>, List<Consumer<EventType>>> src_to_consumers;

Except without the constraint that all producers/consumer-collection pairs must have the same EventType.

Is there a way to do this without casting?

I don't think it's really a good idea to have everything stored in a single map. I believe you'd be better off with alternatives. Maps are not a one-size-fits-all here. If I were you, I'd totally design an event managing class with as many members as needed. If you can reduce all your needs in a single map, go ahead! Just keep the idea open that you are not restricted to a single object, even if it vaguely looks like you can.

However there are already tools that do the whole management of events for you. They're called event-buses. There are a lot of them around and searching for them will give you many results, just pick the one that suits your needs most.

In the end:

There is no way to add this type of constraint on a data type. What I did do is make a new object type "ModuleLinks" that (for my case) binds producers and consumers, and make a collection of those.

class ModuleLinks<EventType>{
    Producer<EventType> producer;
    List<Consumer<EventType>> consumers;
    ...
    }

You can then make your HashMap<Producer, ModuleLinks<EventType>> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM