不能包含不同参数的相同界面?
请考虑以下示例:
public class Sandbox { public interface Listener { public void onEvent(T event); } public interface AnotherInterface extends Listener, Listener { } }
这失败,出现以下错误
/media/PQ-WDFILES/programming/Sandbox/src/Sandbox.java:20: Sandbox.Listener cannot be inherited with different arguments: and public interface AnotherInterface extends Listener, Listener { ^ 1 error
为什么呢? 生成的方法没有重叠。 事实上,这基本上意味着
public interface AnotherInterface { public void onEvent(JPanel event); public void onEvent(JLabel event); }
那里没有重叠。 那为什么会失败呢?
万一你想知道我在做什么并有一个更好的解决方案:我有一堆事件和一个Listener接口,几乎就像上面的Listener
类。 我想创建一个适配器和一个适配器接口,为此我需要使用特定事件扩展所有Listener接口。 这可能吗? 有一个更好的方法吗?
不,你不能。 这是因为只在编译器级别支持generics。 所以你不能这么想
public interface AnotherInterface { public void onEvent(List event); public void onEvent(List event); }
或实现具有多个参数的接口。
UPD
我认为解决方法将是这样的:
public class Sandbox { // .... public final class JPanelEventHandler implements Listener { AnotherInterface target; JPanelEventHandler(AnotherInterface target){this.target = target;} public final void onEvent(JPanel event){ target.onEvent(event); } } ///same with JLabel }
不要忘记,javagenerics是使用类型errasure实现的,但扩展在编译后仍然存在。
所以你要求编译器做什么(在类型擦除之后),
public interface AnotherInterface extends Listener, Listener;
你根本不能做generics。