请考虑以下示例:
public class Sandbox {
public interface Listener<T extends JComponent> {
public void onEvent(T event);
}
public interface AnotherInterface extends Listener<JPanel>, Listener<JLabel> {
}
}
Run Code Online (Sandbox Code Playgroud)
这失败,出现以下错误
/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
Run Code Online (Sandbox Code Playgroud)
为什么呢?生成的方法没有重叠.事实上,这基本上意味着
public interface AnotherInterface {
public void onEvent(JPanel event);
public void onEvent(JLabel event);
}
Run Code Online (Sandbox Code Playgroud)
那里没有重叠.那为什么失败了呢?
万一你想知道我在做什么,并有一个更好的解决方案:我有一堆事件和一个监听器接口,几乎完全像Listener上面的类.我想创建一个适配器和一个适配器接口,为此我需要使用特定事件扩展所有Listener接口.这可能吗?有一个更好的方法吗?
Sta*_*lin 10
不,你不能.这是因为只在编译器级别支持泛型.所以你不能这么想
public interface AnotherInterface {
public void onEvent(List<JPanel> event);
public void onEvent(List<JLabel> event);
}
Run Code Online (Sandbox Code Playgroud)
或实现具有多个参数的接口.
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2764 次 |
| 最近记录: |