I recently stumbled upon a piece of code that would not compile in my Eclipse due to the "same erasure" issue (looked very similar to this one). The guys who wrote the code assured me that it compiles in their local environment and their continuous integration and so I played along to emulate it.
Take a look at this snippet:
package com.mycompany.playground;
import java.util.ArrayList;
import java.util.Collection;
public class GenericsTest {
public static void main (String[] args) {
System.out.println(GenericsTest.doSomething(new ArrayList<A>()));
System.out.println(0 == GenericsTest.doSomething(new ArrayList<C>()));
}
public GenericsTest() {
}
public static String doSomething(Collection<A> listOfA) {
return "has done something to Collection<A>";
}
public static Integer doSomething(Collection<C> listOfC) {
return 0;
}
private class A {
}
private class C {
}
}
Eclipse Helios with 1.6.0_21 JDK as workspace default would not compile it and would complain that Method doSomething(Collection) has the same erasure doSomething(Collection) as another method in type GenericsTest. It would say the same about the other method.
Tried to force Eclipse to run it and saw: Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method doSomething(Collection) in the type GenericsTest is not applicable for the arguments (ArrayList).
Ok. That was to be expected. Now. If I go into my command line and run simple:
javac GenericsTest.java
it compiles. I checked 1.6.0_21 and 1.6.0_06 (the one the guys had in their environments) and neither complained. I copied the class files over to where Eclipse expected them and forced it to run it again.
It prints:
has done something to Collection<A>
true
If I replace the
System.out.println(0 == GenericsTest.doSomething(new ArrayList<C>()));
with
System.out.println(GenericsTest.doSomething(new ArrayList<C>()));
it would still compile without warnings from the command line but give the same "Unresolved compilation problem" when trying to run it.
Two questions here.
Did javac simply outsmart the built-in Eclipse compiler? Looks almost exactly like this previously asked question so I believe I know the answer. (by the way, how can I tell Eclipse to use javac instead?).
Why would javac silently compile what java will then fail to run (second scenario with the {0 ==} "hint" removed?