Implementing Generic Interface in Java -
i have java generics question hoping answer. consider 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 implement handles interface 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 generic. able accomplish c#, cannot figure workaround in java without using reflection or instanceof , casting.
is there way in java implement handles interface using both generic interfaces? or perhaps way write handles interface end result can accomplished?
you can't in java. can implement 1 concrete realization of same generic interface. 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){} }
Comments
Post a Comment