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

后端 未结 1 2018
离开以前
离开以前 2021-01-13 05:36

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 {
         


        
1条回答
  •  被撕碎了的回忆
    2021-01-13 06:04

    Wildcards are limited in that they break recursive expressions like T extends X 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.
    2. The method p takes an argument of type T (declared by p), which also is or extends N.
    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);
    }
    

    0 讨论(0)
提交回复
热议问题