开发者

Can't include the same interface with different parameters?

Consider the following example:

开发者_开发百科
public class Sandbox {
    public interface Listener<T extends JComponent> {
        public void onEvent(T event);
    }

    public interface AnotherInterface extends Listener<JPanel>, Listener<JLabel> {
    }
}

This fails with the following error

/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

Why though? There is no overlap in the generated methods. As a matter of fact, that essentially means

public interface AnotherInterface {
    public void onEvent(JPanel event);
    public void onEvent(JLabel event);
}

No overlap there. So why is it failing?


In case your wondering what I'm doing and have a better solution: I have a bunch of Events and a Listener interface that's almost exactly like the Listener class above. I'm wanting to create an adapter and an adapter interface, and for that I need to extend all the Listener interfaces with a specific event. Is this possible? Is there a better way to do this?


No. You cant. It's because generics are supported only at compiler level. So you can't do thinks like

public interface AnotherInterface {
    public void onEvent(List<JPanel> event);
    public void onEvent(List<JLabel> event);
}

or implements interface with several parameters.

upd

I think workaround will be like this:

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
}


Don't forget that in java generics are implemented using type errasure, yet extension remains after compilation.

So what you are asking the compiler to do (after type erasure is),

public interface AnotherInterface extends Listener, Listener;

which you simply can't do generics or not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜