考虑以下示例:
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 接口(interface)。我想创建一个适配器和一个适配器接口(interface),为此我需要使用特定事件扩展所有 Listener 接口(interface)。这可能吗?有更好的方法吗?
最佳答案
没有。你不能。 这是因为仅在编译器级别支持泛型。所以你不能这样想
public interface AnotherInterface {
public void onEvent(List<JPanel> event);
public void onEvent(List<JLabel> event);
}
或实现带有多个参数的接口(interface)。
更新
我认为解决方法是这样的:
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 - 不能包含具有不同参数的相同接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4420636/