不能包含具有不同参数的相同接口?
问题描述:
请看下面的例子:不能包含具有不同参数的相同接口?
public class Sandbox {
public interface Listener<T extends JComponent> {
public void onEvent(T event);
}
public interface AnotherInterface extends Listener<JPanel>, Listener<JLabel> {
}
}
这失败,出现以下错误
/media/PQ-WDFILES/programming/Sandbox/src/Sandbox.java:20: Sandbox.Listener cannot be inherited with different arguments: <javax.swing.JPanel> and <javax.swing.JLabel>
public interface AnotherInterface extends Listener<JPanel>, Listener<JLabel> {
^
1 error
但为什么呢?生成的方法没有重叠。事实上,这实际上意味着
public interface AnotherInterface {
public void onEvent(JPanel event);
public void onEvent(JLabel event);
}
那里没有重叠。那么为什么它失败了?
如果你想知道我在做什么,有一个更好的解决方案:我有一大堆的活动和一个监听器的界面,几乎完全一样上面的Listener
类。我想创建一个适配器和一个适配器接口,为此我需要扩展所有的Listener接口和一个特定的事件。这可能吗?有一个更好的方法吗?
答
不,你不能。 这是因为泛型只支持编译器级别。所以你不能这样想,就像
public interface AnotherInterface {
public void onEvent(List<JPanel> event);
public void onEvent(List<JLabel> event);
}
或实现与几个参数的接口。
UPD
我认为解决方法将是这样的:
public class Sandbox {
// ....
public final class JPanelEventHandler implements Listener<JPanel> {
AnotherInterface target;
JPanelEventHandler(AnotherInterface target){this.target = target;}
public final void onEvent(JPanel event){
target.onEvent(event);
}
}
///same with JLabel
}
答
不要忘记,在Java泛型使用类型错误实现,但扩展仍然编译后。
你问那么编译器执行(后类型擦除是),
public interface AnotherInterface extends Listener, Listener;
,你根本就做不到泛型与否。
+0
我忘了类型擦除。你知道一种替代方法来完成我想要完成的任务吗? – TheLQ 2010-12-12 16:38:11
+0
'一级实现二,三{ } 接口其他
啊,我忘记了类型擦除。你知道另一种方法来完成我想要做的事吗? – TheLQ 2010-12-12 16:38:47
@TheLQ,已更新。 – 2010-12-12 17:11:49
@Stas每个事件看起来像是一吨代码(〜50)。也许我应该回到显式创建每个事件的侦听器? – TheLQ 2010-12-12 17:22:53