Why does Eclipse compile this, but javac not?

We have some unit tests that compile and run fine in Eclipse 3.4, but when we try to compile them using javac, it fails. I managed to translate the code to something small and autonomous, so it has no external dependencies. The code itself will not make much sense, because all this is out of context, but it does not matter - I just need to find out why javac does not like:

public class Test { public void test() { matchOn(someMatcher().with(anotherMatcher())); } void matchOn(SubMatcher matcher) {} SubMatcher someMatcher() { return new SubMatcher(); } Matcher anotherMatcher() { return null; } } interface Matcher <U, T> {} class BaseMatcher implements Matcher { public BaseMatcher with(Matcher<?,?> matcher) { return this; } } class SubMatcher extends BaseMatcher { @Override public SubMatcher with(Matcher matcher) { return this; } } 

I tried with JDK 1.5.0_10 and 1.6.0_13 with the same result:

 Test.java:6: matchOn(test.SubMatcher) in test.Test cannot be applied to (test.BaseMatcher) matchOn(someMatcher().with(anotherMatcher())); ^ 1 error 

I think this is perfectly valid Java. The SubMatcher.with () method returns a more specific type than BaseMatcher.with (), but the compiler seems to think the return type is BaseMatcher. However, it is possible that the Eclipse compiler incorrectly resolves something that it should not be.

Any ideas?

+7
java compiler-construction jls
source share
4 answers

in BaseMatcher you need to specify type parameters:

 public SubMatcher with(Matcher<?, ?> matcher) { 

make javac match your with method

PS

imho - eclipse compiler error

+7
source share

I did this successfully by adding <?,?> the Matcher in SubMatcher.with :

 class SubMatcher extends BaseMatcher { @Override public SubMatcher with(Matcher<?,?> matcher) { return this; } } 

Without this, the method signature is different from the base. I wonder if there is an error in the @Override check that does not notice this.

+7
source share

Check which jre or jdk you are compiling on both Eclipse and the terminal. Perhaps this could be a version issue.

0
source share

Works for me:

 $ java -version
 openjdk version "1.7.0-internal"
 OpenJDK Runtime Environment (build 1.7.0-internal - **** - 2009_07_23_10_21-b00)
 OpenJDK 64-Bit Server VM (build 16.0-b06, mixed mode)
 $ javac -XDrawDiagnostics Test.java 
 $

I vaguely remember such a bug report, but I can’t give you a link to it right now.

0
source share

All Articles