Implementing Generic Interface in Java

后端 未结 7 2016
忘了有多久
忘了有多久 2020-12-24 12:38

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

public interface Event{}
public class AddressChanged implemen         


        
7条回答
  •  春和景丽
    2020-12-24 12:52

    It isn't allowed because Java erases generic signatures during compilation. The interface method will actually have the signature

    public void handle(Object event);
    

    So you have two choices. Either implement separate Handlers for different events:

    public class AddressChangedHandler implements Handles{ /* ... */ }
    public class AddressDiscardedHandler implements Handles{ /* ... */ }
    

    or implement one handler for all but check the type of the incoming event:

    public void handle(Event e){
      if (e instanceof AddressChanged) {
         handleAdressChanged(e);
      }
      else if (e instanceof AddressDiscareded) {
         handleAdressDiscarded(e);
      }
    }
    

提交回复
热议问题