Java wildcards don't allow type-casting
Question
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< ?>> ?
Solution
You should use <? 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..
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow