Limited wildcards not compiling

I have a code like this:

interface InterfaceA { ... }

interface InterfaceB { ... }

class ClassA {
    public void methodA(Class<? extends InterfaceB> clazz) { ... }
}

class ClassB<P extends InterfaceA & InterfaceB> {
    public void methodB(P p) {
        new ClassA().methodA(p.getClass());
    }
}

Question: why the compiler does not allow passing p.getClass()method as an argument methodA- mesage error:

The method methodB(Class<? extends InterfaceB>) in the type ClassA is not applicable for the arguments (Class<capture#1-of ? extends InterfaceA>)

Clear that type Pextends InterfaceBin ClassB, so I have no idea why it doesn't work.

+4
source share
1 answer

Return type Object#getClass()is

The actual type of result Class<? extends |X|>, where |X|is the erasure of the static type of the expression on which it getClassis called.

Erasing a static type p(the expression being called getClass) is an erasure

P extends InterfaceA & InterfaceB

InterfaceA. " Java", Erasure

(§4.4) .

Class<? extends InterfaceB>, Class<? extends InterfaceA>. .

,

class ClassB<P extends InterfaceB & InterfaceA> {
+3

Source: https://habr.com/ru/post/1608051/


All Articles