Can't include the same interface with different parameters?

前端 未结 2 1221
野性不改
野性不改 2021-01-04 18:34

Consider the following example:

public class Sandbox {
    public interface Listener {
        public void onEvent(T event);
             


        
相关标签:
2条回答
  • 2021-01-04 18:54

    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
    }
    
    0 讨论(0)
  • 2021-01-04 19:07

    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 讨论(0)
提交回复
热议问题