Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 547
whistlenuts Avatar asked Dec 01 '10 15:12

whistlenuts


People also ask

Can we use generics with interface in Java?

If a class implements generic interface, then class must be generic so that it takes a type parameter passed to interface.


1 Answers

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){} } 
like image 172
Stan Kurilin Avatar answered Oct 02 '22 15:10

Stan Kurilin