javac's "-source" changes your class behavior ???
I came across this yesterday. Very wired!
I took quite time to understand what was going wrong. My JUnit tests worked fine in IDEA but they were failing when run from command line with ANT. Then I figured out that the only difference was the language compatibility level set in IDEA to "1.4" and ommited (set do default) in ANT.
Below is an example that you can try. I work on WinXP, Java HotSpot(TM) Client VM (build 1.4.2_06-b03, mixed mode).
public class ShowSourceImpact {
public static void main(String[] args) {
final Integer val = new Integer(1);
Sample s = new Sample() {
Integer createI() {
return val;
}
};
System.out.println("'i' is: " + s.getI());
System.out.println("'i' should be: " + val);
}
static class Sample {
private Integer i = null;
public Sample() {
i = createI();
}
Integer createI() {
return new Integer(-1);
}
public Integer getI() {
return i;
}
}
}Then, when you compile it like
javac ShowSourceImpact.java and run it you'll see:'i' is: null
'i' should be: 1
When you compile it with
javac -source 1.4 ShowSourceImpact.java you'll get the following:'i' is: 1
'i' should be: 1
So the problem is when you have an
inner class and you overwrite its methods in such a way that they rely on final variables declared in the outer method. See createI() method in the example above. For "1.3" source code it seems that the value of these final variables are null inside the inner class. This works ok with "1.4" source.
I thought that the "-source" 1.3 vs 1.4 vs 1.5 was only about the new keywords introduced to the language. However with the example above it looks there is more to that.
Anyone has any good explanation for that?

<< Home