How to interate a ArrayList>

2019-07-10 16:10发布

I have an ArrayList<Class<? extends IMyInterface>> classes = new ArrayList<>();. When I try to iterate it, I get:

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

My iteration

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

Red code warning highlight (Android Studio)

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

I would like to

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

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

ERROR

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

How can I go about iterating through it?

Thank you all in advance.

2条回答
相关推荐>>
2楼-- · 2019-07-10 16:43

You want to iterate on instances of IMyInterface as you want to invoke a specific method of IMyInterface :

    View revPluggableViewLL = myClass.getMyInterfaceMethod();

The problem is that you declared a List of Class instances :

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

It doesn't contain any instance of IMyInterface but only Class instances.

To achieve your need, declare a list of IMyInterface :

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

And use it in this way :

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

Note that this check is not required :

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

You manipulate a List of IMyInterface, so elements of the List are necessarily instances of IMyInterface.

查看更多
【Aperson】
3楼-- · 2019-07-10 17:02

myClass is an instance of Class, which doesn't implement IMyInterface (even if it's Class<IMyInterface>). Therefore you can never execute getMyInterfaceMethod() on myClass.

查看更多
登录 后发表回答