incompatible types and fresh type-variable

后端 未结 2 1054
长情又很酷
长情又很酷 2020-12-03 14:02

I get the following compilation message:

[javac]   ... error: incompatible types
[javac]         exceptionClassHolder = new Holder<>( (new Exception())         


        
2条回答
  •  无人及你
    2020-12-03 14:59

    Unfortunately, the existing answers don't explain what's going on here. First, the solution is to simply specify the type argument to Holder:

    Holder> exceptionClassHolder;
    exceptionClassHolder =
            new Holder>(new Exception().getClass());
    

    The reason your version didn't work is because new Exception().getClass() returns a Class, where ? is a wildcard capture (referred to in the compiler error message as CAP#1). Since you use the "diamond operator" with new Holder<>, the compiler infers Class for T and so Holder> is the type of the created object.

    However, this doesn't match your declared type of Holder>. It uses a nested wildcard, which doesn't capture: while CAP#1 extends Exception is some specific type extending Exception, the nested ? extends Exception represents literally any type extending Exception.

    And while Class is a subtype of Class, Holder> is not a subtype of Holder> because generics aren't covariant, so the assignment fails.

    By manually specifying Class for T, you help the compiler avoid this "trap".

    See my similar answers on these posts:

    • Java: Wildcard Types Mismatch Results in Compilation Error
    • Bounded-wildcard related compiler error

提交回复
热议问题