在Java中实现通用接口 [英] Implementing Generic Interface in Java

查看:339
本文介绍了在Java中实现通用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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);
}

我想实现这样的Handles接口:

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

但是java不允许实现句柄两次使用通用。我能用C#完成这个工作,但是不能在没有使用Reflection或instanceof和casting的情况下在java中找到解决方法。

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.

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

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?

推荐答案

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

You can't do that in Java. You can only implement one concrete realization of the same generic interface. I would do this 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){}
}

这篇关于在Java中实现通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆