2015-01-16 2 views
2

다음 인터페이스가 있습니다 : interface Nofifier<T> { }.인터페이스 구현의 일반 매개 변수 가져 오기

다음과 같은 구현이 있습니다 : class MyClass implements Notifier<String>, Notifier<Integer> { }.

내가에서 조회 할 수있는 방법이 있나요 : NotifierMyClass 그 구현의 종류를 얻을 수

MyClass instance = new MyClass(); 
Class<?> clazz = instance.getClass(); 
// ... 

은?

답변

3

예 - Class.getGenericInterfaces()으로 전화하여 Type[]을 반환 할 수 있습니다. 여기에는 형식 인수 정보가 포함됩니다.

완벽한 예 :

import java.lang.reflect.Type; 

interface Notifier<T> { } 

class Foo implements Notifier<String> { 
} 

class Test { 
    public static void main(String[] args) { 
     Class<?> clazz = Foo.class; 
     for (Type iface : clazz.getGenericInterfaces()) { 
      System.out.println(iface); 
     } 
    } 
} 

그러나, 당신은 그래서 당신의 class MyClass implements Notifier<String>, Notifier<Integer> 컴파일되지해야한다, 어쨌든 하나 개의 클래스에 두 번 같은 인터페이스를 구현할 수 없습니다. (§

클래스가 동시에 같은 일반적인 인터페이스가 다른 매개 변수화 두 인터페이스 유형의 하위 유형하지 않을 수 있습니다 :

error: Notifier cannot be inherited with different arguments: 
    <java.lang.String> and <java.lang.Integer> 

JLS 8.1.5에서 : 당신은 같은 오류가 발생한다 9.1.2) 또는 generic 인터페이스의 매개 변수화의 부속 유형과 동일한 일반 인터페이스의 이름을 지정하는 원시 유형이거나 컴파일 타임 오류가 발생합니다.