Sorry for the vague title. I have this piece of code which compiles on Eclipse Juno (4.2) but not javac (1.7.0_09):
package test;
public final class Test {
public static class N<T extends N<T>> {}
public static class R<T extends N<T>> {
public T o;
}
public <T extends N<T>> void p(final T n) {}
public void v(final R<?> r) {
p(r.o); // <-- javac fails on this line
}
}
The error is:
Test.java:13: error: method p in class Test cannot be applied to given types; p(r.o); ^ required: T found: N<CAP#1> reason: inferred type does not conform to declared bound(s) inferred: N<CAP#1> bound(s): N<N<CAP#1>> where T is a type-variable: T extends N<T> declared in method <T>p(T) where CAP#1 is a fresh type-variable: CAP#1 extends N<CAP#1> from capture of ? 1 error
So the questions are:
Is this a
javac
bug or Eclipse bug?Is there any way to make this compile on
javac
, without changing the signature of thev
method (i.e. keep the wildcard)?I know changing it to
<T extends N<T>> void v(final R<T> r)
does make it compile, but I would like to know if there's way to avoid this first. Also, the methodp
cannot be changed to<T extends N<?>> void p(final T n)
because the content have types which requires the exact constraintT extends N<T>
.
Wildcards are limited in that they break recursive expressions like
T extends X<T>
that type parameters allow. We know what you're trying to do is safe based on the following:r.o
is of typeT
(declared byR
), which is or extendsN<T>
.p
takes an argument of typeT
(declared byp
), which also is or extendsN<T>
.r
is typed asR<?>
, a callp(r.o)
should theoretically be legal.This is possibly the reasoning of the eclipse compiler (known to make correct allowances for certain nuances of generics where javac doesn't).
Assuming you want to compile with javac and can't change the signature of
v
like you mentioned, the best you can do is resort to using a raw type, which "opts out" of generic type checking: