Search code examples
javagenericscqrs

Implementing Generic Interface in Java


I have a Java generics question I was hoping someone could answer. Consider the following code:

public interface Event{}
public class AddressChanged implements Event{}
public class AddressDiscarded implements Event{}

public interface Handles<T extends Event>{
    public void handle(T event);
}

I want to implement this Handles interface like this:

public class AddressHandler implements Handles<AddressChanged>, Handles<AddressDiscarded>{
    public void handle(AddressChanged e){}
    public void handle(AddressDiscarded e){}
}

But java doesn't allow implementing Handles twice using the Generic. I was able to accomplish this with C#, but cannot figure a workaround in java without using Reflection or instanceof and casting.

Is there a way in java to implement the Handles interface using both generic interfaces? Or perhaps another way to write the Handles interface so the end result can be accomplished?


Solution

  • You can't do that in Java. You can only implement one concrete realization of the same generic interface. I would do this instead:

    public class AddressHandler implements Handles<Event>{
        public void handle(Event e){
          if(e instanceof AddressDiscarded){
             handleDiscarded(e);
          } else if(e instanceof AddressChanged){
             handleChanged(e);
          }
        }
        public void handleDiscarded(AddressDiscarded e){}
        public void handleChanged(AddressChanged e){}
    }