I am still experimenting with how Java handles generics. I stumbled upon the fact/issue/thing that if you have a generic interface like A<T>
, you cannot really check afterwards if some object is actually implementing A<B>
or A<C>
.
I wondered if that could cause actual problems.
Now I have tried this code:
static interface A<T> { void foo(T obj); }
static class B implements A<B> {
public void foo(B obj) { obj.bar(); }
void bar() {}
}
static {
assert (new B() instanceof A<?>);
((A<?>) new B()).foo(new Object());
}
This gives me this error (for the foo
-call):
The method foo(capture#1-of ?) in the type Main.A<capture#1-of ?> is not applicable for the arguments (Object)
I wonder why that is. Eclipse tells me that the signature of foo
after the cast to A<?>
is foo(? obj)
which I thought is the same as foo(Object obj)
.
The assert
succeeds.
What I tried to figure out is at what point exactly does it cast the object when I call the foo
function.
Also, how can I call foo
from A<?>
? This is the thing I actually need to be able to do. Or is that impossible with any other parameter than null
?
A more real-world example where I actually wonder about this: I use the Comparable<T>
interface a lot. That case is actually even more complicated; I might open another question about that if this here doesn't answer it.