Enhanced for loop compiling fine for JDK 8 but not 7

后端 未结 6 1034
Happy的楠姐
Happy的楠姐 2021-01-03 18:36

Consider the following code snippet, I stumpled upon after some refactoring, when checkin why the build server reported a broken build but it was fine in my IDE:

<         


        
6条回答
  •  花落未央
    2021-01-03 18:55

    Although I think the other answers are correct, let me be devil's advocate and offer the opposite view.

    Obviously JDK 7 parses the foreach loop in such a way that the variable 'text' is also in scope after the ':'. To test this, I wrote the following method. It compiles and runs just fine in Java 1.7:

    public static void main(String[] args) {
        for (String text : new String[] {text = "hello", text, text, text})
            System.out.println(text);
    }
    

    Although others have said this is a bug in jdk 1.7 (and it probably is), I couldn't find anywhere in the JLS that specifically says the variable just declared is not in scope after the ':'. If it's not a bug, then Java 8 breaks compatibility.

提交回复
热议问题