2010-12-12 2 views
10

다음 예제를 고려하십시오.매개 변수가 다른 동일한 인터페이스를 포함 할 수 없습니까?

public class Sandbox { 
    public interface Listener<T extends JComponent> { 
     public void onEvent(T event); 
    } 

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

이것은 다음 오류와 함께 실패합니다.

/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 

왜 그래도됩니까? 생성 된 메소드에는 겹침이 없습니다. 사실, 그것은 본질적으로

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

를 의미합니다. 그렇다면 왜 실패 하는가?


내가하고있는 일에 대해 궁금한 점이 있으면 더 좋은 해결책이 있습니다. 위의 Listener 클래스와 거의 비슷한 Listener 인터페이스와 이벤트 묶음이 있습니다. 나는 어댑터와 어댑터 인터페이스를 만들고 싶다. 그래서 모든 리스너 인터페이스를 특정 이벤트로 확장해야한다. 이것이 가능한가? 이 작업을 수행하는 더 좋은 방법이 있습니까?

답변

10

아니요. 제네릭은 컴파일러 수준에서만 지원되기 때문입니다. 따라서 당신은 생각할 수 없습니다.

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

또는 몇 가지 매개 변수를 사용하여 인터페이스를 구현합니다.

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

아, 타입 지우기를 잊어 버렸습니다. 내가하고 싶은 일을 성취하기위한 다른 방법을 알고 있습니까? – TheLQ

+0

@TheLQ, 업데이트 됨. –

+0

@Stas 그건 이벤트 당 코드 톤 (~ 50)처럼 보입니다. 어쩌면 이벤트별로 청취자를 명시 적으로 작성해야할까요? – TheLQ

3

자바 제네릭은 errasure를 사용하여 구현되지만 확장 후에도 컴파일이 유지된다는 것을 잊지 마십시오. 당신은 단순히 제네릭 여부를 할 수없는 당신 (유형 소거 후) 할 컴파일러를 요구하고 그래서

,

public interface AnotherInterface extends Listener, Listener; 

.

+0

나는 형의 삭제에 대해 잊었 :

UPD는 내가 해결 방법은 다음과 같이 될 것이라 생각합니다. 내가 성취하고자하는 것을 성취하기위한 다른 방법을 알고 있습니까? 변경 한'Object' - – TheLQ

+0

'클래스 하나는 2, 3 { } 인터페이스 다른 { } 인터페이스 두 개의 다른 { } 인터페이스 세 기타 { 을}'확장 확장 구현 다른 일은 오류가 발생합니다. 따라서 인터페이스가 중복되어 확장되는 것이 아니며 Generics를 사용하여 특별히 수행해야합니다. – Nicole

관련 문제