简体   繁体   中英

List of Class<? extends Foo> incompatible types

I'm working on this piece of code:

List<Class<? extends Foo>> models = new ArrayList<>();
    if (bar == 0)
        models = getRandomBlas(); // returns List<Bla>
    else 
        models = getRandomBlubs(); // returns List<Blub>

with:

public class Bla extends Foo { ... }
public class Blub extneds Foo { ... }

But I'm getting an Incompatible types: Found: 'java.util.List<Bla>', required: 'java.util.List<java.lang.Class<? extends Foo>' Incompatible types: Found: 'java.util.List<Bla>', required: 'java.util.List<java.lang.Class<? extends Foo>'

Has anyone got an idea? To my knowledge, this is how the ? extends ? extends should work...

You're right. That is how ? extends ? extends works, but your list wants Class objects.

  • List<Class<? extends Foo>> List<Class<? extends Foo>> can contain Class objects that represent subtypes of Foo ( Foo.class , Bla.class , Blub.class ).

  • List<? extends Foo> List<? extends Foo> can contain objects that are subtypes of Foo .

You want the second version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM