Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java CRTP and Wildcards: Code compiles in Eclipse but not `javac`

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:

  1. Is this a javac bug or Eclipse bug?

  2. Is there any way to make this compile on javac, without changing the signature of the v 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 method p cannot be changed to <T extends N<?>> void p(final T n) because the content have types which requires the exact constraint T extends N<T>.

like image 915
kennytm Avatar asked Nov 03 '12 17:11

kennytm


1 Answers

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:

  1. r.o is of type T (declared by R), which is or extends N<T>.
  2. The method p takes an argument of type T (declared by p), which also is or extends N<T>.
  3. So even though r is typed as R<?>, a call p(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:

public void v(final R<?> r) {
    //necessary to placate javac - this is okay because [insert above reasoning]
    @SuppressWarnings("rawtypes")
    N nRaw = r.o;
    p(nRaw);
}
like image 90
Paul Bellora Avatar answered Oct 06 '22 05:10

Paul Bellora