java – 如何多次实现相同的界面,但是用不同的泛型?
发布时间:2020-12-14 05:32:13 所属栏目:Java 来源:网络整理
导读:这个问题在这里已经有一个答案: How to make a Java class that implements one interface with two generic types?6 我有以下界面,我想在我的类中多次实现: public interface EventListenerT extends Event{ public void onEvent(T event);} 现在,我想通
这个问题在这里已经有一个答案:>
How to make a Java class that implements one interface with two generic types?6
我有以下界面,我想在我的类中多次实现: public interface EventListener<T extends Event> { public void onEvent(T event); } 现在,我想通过以下方式实现这个界面: class Foo implements EventListener<LoginEvent>,EventListener<LogoutEvent> { @Override public void onEvent(LoginEvent event) { } @Override public void onEvent(LogoutEvent event) { } } 但是,这给我的错误:复制类com.foo.EventListener在行上: class Foo implements EventListener<LoginEvent>,EventListener<LogoutEvent> 可以用不同的泛型实现接口两次吗?如果没有,下一个最接近我可以做什么来实现我在这里做什么? 解决方法
您需要使用内部或匿名类.例如
class Foo { public EventListener<X> asXListener() { return new EventListener<X>() { // code here can refer to Foo } } public EventListener<Y> asYListener() { return new EventListener<Y>() { // code here can refer to Foo } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |