简体   繁体   中英

Java wildcards don't allow type-casting

interface Message<T, L> {
}

interface Foo<T> {
    void frob(Message<T, Foo<?>> message);
}

class AuxiliaryFoo implements Foo<Integer> {
    @Override
    public void frob(Message<Integer, Foo<?>> message) { }
}

class MainFoo implements Foo<Object> {
    @Override
    public void frob(Message<Object, Foo<?>> message) {
        new AuxiliaryFoo().frob(new Message<Integer, MainFoo>() {});
    }
}

The Java compiler tells me that actual argument < anonymous Message< Integer, MainFoo >> cannot be converted to Message< Integer, Foo< ?>> by method invocation conversion .

Why?

And what can be converted to Message< Integer, Foo< ?>> ?

You should use <? extends Foo<?>> <? extends Foo<?>>

interface Foo<T> {     
    void frob(Message<T, ? extends Foo<?>> message); 
} 

Also, something worthy to keep in mind when dealing with generics is the PECS rule: Producer Extends, Consumer Super though it doesn't directly belong here, but I can't say that it doesn't belong here at all..

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