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?
If a class implements generic interface, then class must be generic so that it takes a type parameter passed to interface.
Going after @Amir Raminfar, you can use visitor pattern
interface Event{ void accept(Visitor v); } interface Visitor { void visitAddressChanged(AddressChanged a); void visitAddressDiscarded(AddressDiscarded a); } class AddressChanged implements Event{ @Override public void accept(Visitor v) { v.visitAddressChanged(this); } } class AddressDiscarded implements Event{ @Override public void accept(Visitor v) { v.visitAddressDiscarded(this); } } class AddressHandler implements Visitor { void handle(Event e){ e.accept(this); } public void visitAddressChanged(AddressChanged e){} public void visitAddressDiscarded(AddressDiscarded e){} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With