2017-11-02 5 views
2

나는 ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>();을 가지고 있습니다. 나는 그것을 반복 할 때 내가 얻을 :ArrayList를 중개하는 방법 <Class <? extends IMyInterface >>

Incopatible types: 
Required: java.lang.Class <? extends IMyInterface> 
Found: IMyInterface 

이 반복

for (IMyInterface iMyInterface : IMyInterface.getMyPluggables()) {} 

레드 코드 경고 하이라이트 (안드로이드 스튜디오)

Error:(35, 90) error: incompatible types: Class<? extends IMyInterface> cannot be converted to IMyInterface 

내가

싶습니다 내
ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>(); 

for (Class<? extends IMyInterface> myClass : classes) { 
    if (myClass instanceof IMyInterface) { 
     View revPluggableViewLL = myClass.getMyInterfaceMethod(); 
    } 
} 

Inconvertible types; cannot cast 'java.lang.Class<capture<? extends com.myapp.IMyInterface>>' to 'com.myapp.IMyInterface' 

가 어떻게 그것을 통해 반복에 대해 갈 수 ERROR?

감사합니다. 당신은 IMyInterface의 특정 메소드를 호출 할로 IMyInterface의 인스턴스에서 반복 할

+0

당신은'ArrayList >''ArrayList '가 아닙니다. 그리고 그런데, 이것은 당신이 원하는 것이 아닙니다 ...'클래스'는 타입을 나타내는 인스턴스입니다. 타입 자체의 인스턴스는 아닙니다. 그러므로'instanceof IMyInterface'는 결코 사실이 아닙니다. – AxelH

답변

5

:

ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>(); 

그것을 :

View revPluggableViewLL = myClass.getMyInterfaceMethod(); 

문제는 당신이 ListClass의 인스턴스를 선언 한 것입니다 IMyInterface의 인스턴스를 포함하지 않고 Class 인스턴스 만 포함합니다.

List<IMyInterface> instances = new ArrayList<>(); 

그리고이 방법을 사용합니다 :

for (IMyInterface myInterface : instances) { 
    View revPluggableViewLL = myInterface.getMyInterfaceMethod(); 
} 

참고이 검사가 필요하지 않음 :

if (myClass instanceof IMyInterface) { 
    View revPluggableViewLL = myClass.getMyInterfaceMethod(); 
} 

IMyInterface의 목록을 선언, 당신의 필요를 달성하기 위해

ListIMyInterface을 조작합니다. List의 요소는 반드시 IMyInterface의 인스턴스입니다.

+0

응답 @ davidxxx 주셔서 감사합니다. 이것으로,'IMyInterface' 인스턴스를'List instances = new ArrayList <>();'에 추가 할 수 없습니다. 나는'ArrayList > instances = new ArrayList <>();'내가 할 수있는'instances.add (AClassOfIMyInterface.class);'. 그것을 고칠 수있는 제안이 있습니까? 다시 감사합니다. –

+0

당신은 환영합니다.왜 당신은 당신의 목록에'클래스'가 필요하다고 생각합니까? '클래스'는 클래스 구조/정의를 나타내며'IMyInterface'의 인스턴스는 아닙니다. – davidxxx

+0

이것은 이전에 [ArrayList에 인터페이스를 구현하는 클래스를 추가하는 방법]이라는 질문에 대한 후속 조치입니다. (https://stackoverflow.com/questions/47067888/how-to-add-a-class- 구현 인터페이스 - - - arraylist), 나는 [Ramanlfc의 대답] (https://stackoverflow.com/a/47068064/3663765)을 수락했습니다. –

2

myClass은 인데도 IMyInterface을 구현하지 않는 Class의 인스턴스입니다. 따라서 에 getMyInterfaceMethod()을 실행할 수 없습니다.

관련 문제