Java: Wildcard Types Mismatch Results in Compilation Error

前端 未结 1 1576
一整个雨季
一整个雨季 2020-12-19 13:22

I\'ve created a factory class in my project which would allow me (in theory) to create managers for any (supported) given type. Interacting with the manager allows me to alt

1条回答
  •  借酒劲吻你
    2020-12-19 13:50

    Use the following:

    IManager> test3Manager =
            Factory.>createManager(test3);
    

    This is just a case of the compiler's type inference falling on its face, so it's necessary explicitly provide the type argument for T.

    More technically:

    test3 is declared to have the type IAnotherRandomType, where ? is a wildcard capture - a sort of one-use type parameter representing some specific unknown type. That's what the compiler's referring to when it says capture#1-of ?. When you pass test3 into createManager, T gets inferred as IAnotherRandomType.

    Meanwhile, test3Manager is declared to have the type IManager>, which has a nested wildcard - it does not behave like a type parameter but rather represents any type.

    Since generics aren't covariant, the compiler can't convert from IManager> to IManager>.

    More reading on nested wildcards:

    • Multiple wildcards on a generic methods makes Java compiler (and me!) very confused
    • Java Generic List>
    • Which super-subset relationships exist among wildcards?

    0 讨论(0)
提交回复
热议问题