在 Java 中实现通用接口

2022-09-01 12:05:15

我有一个Java泛型问题,我希望有人能回答。请考虑以下代码:

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

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

我想像这样实现这个句柄接口:

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

但是java不允许使用General实现两次句柄。我能够使用C#完成此操作,但是如果不使用Refleprem或exjectof和cast,就无法在java中找到解决方法。

在Java中,有没有办法使用两个通用接口来实现Handles接口?或者也许是编写句柄接口的另一种方法,以便可以完成最终结果?


答案 1

追逐@Amir拉明法尔,你可以使用访客模式

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){}
}

答案 2

你不能在Java中做到这一点。您只能实现同一通用接口的一个具体实现。我会这样做:

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){}
}

推荐