Search code examples
javatype-safety

TypeSafe EventDispatcher with data in Java


I tried to implement a simple typesafe event dispatcher with data, i.e. in addition to the event one can deliver any data. I found a lot of type safe event dispatcher questions or any other examples but no one seems to solve my question. This is what I got so far:

public interface EventDispatcher {
    <T> void registerCallback(Event<T> event, BiConsumer<T, Long> callback);
    <T> void event(Event<T> event, T t, long param);
}

and

public interface Event<T> {
    String name();
}

This actually works (I have a working implementation of the EventDispatcher interface), the Event interface can be 'implemented' by using Enums like this:

public enum StringEvent implements Event<String> {
    EVENT1,
    EVENT2
}

What I'm not happy with is the fact, that I have to create different enums for all the objects I want to deliver to the dispatcher. I was thinking about something like this

public enum Events {
    EVENT1(String.class),
    EVENT2(String.class),
    EVENT3(Long.class);

    Events(Class<T> clazz) {
        ...
    }

    ...
}

But this does not seem to lead to an event object which can be used in the event dispatcher... Any ideas?


Solution

  • My best approach so far is:

    public class Events {
        private static <T> Event<T> create(String name) {
            return () -> name;
        }
    
        public static final Event<String> EVENT1 = create("Event1");
        public static final Event<String> EVENT2 = create("Event2");
        public static final Event<Long> EVENT3 = create("Event3");
    }
    

    More verbose than just enums but after I wrote down all events, it can be used like enums. But I'm still open to better solutions...