请考虑以下示例:
- public class SandBox {
- public interface Listener<T extends JComponent> {
- public void onEvent(T event);
- }
- public interface AnotherInterface extends Listener<JPanel>,Listener<JLabel> {
- }
- }
- public interface AnotherInterface {
- public void onEvent(JPanel event);
- public void onEvent(JLabel event);
- }
没有重叠.那为什么会失败呢?
如果你想知道我在做什么,并且有一个更好的解决方案:我有一堆事件和一个监听器接口,几乎完全像上面的监听器类.我想要创建一个适配器和适配器接口,为此我需要扩展所有的监听器接口与一个特定的事件.这可能吗?有没有更好的方法来做到这一点?
解决方法
不,你不行
这是因为泛型仅在编译器级才支持.所以你不能这样想
这是因为泛型仅在编译器级才支持.所以你不能这样想
- 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
- }