Found interesting thing while compile the following piece of code:
1 class A {
2
3 private B line;
4
5 public void foo() {
6 for (Integer line : line.getElements()) {
7
8 }
9 }
10 }
11
12 class B {
13
14 List<Integer> getElements() {
15 return null; // doesn't matter
16 }
17 }
Pay attention to line 6: we see that variable name is equal to field name. IntelliJ Idea 11 ignores this and think there is no trouble here. But java compiler tells me that ‘line doesn’t have method getElements’. So, two questions:
- Should I submit a bugreport in Idea?
- Why the error message from Java is like this? Isn’t it able to detect the mistake? What mechanism is working here? Eclipsing of field variable?
This may be a bug in the Java compiler you are using. According to the Java Language Specification (section 14.14.2), the scope of the variable in an enhanced
forstatement is the contained statement. (This seems to exclude the iterable or array expression to the right of the:.)You can work around the problem by using
this.line.getElements().EDIT
Just for kicks, I submitted this as a bug report to Sun. We’ll see whether the Java engineers think it’s a bug in the JLS or in javac (or if they have some other explanation). The bug id is 7139681, although it won’t be posted to the external database for a couple of days.