Enhanced for loop compiling fine for JDK 8 but not 7

后端 未结 6 1032
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 19:16

    This should actually compile fine for JDK 7 and 8.

    Quoting JLS section 14.14.2 (which is the same for the Java 7 specification):

    The enhanced for statement is equivalent to a basic for statement of the form:

    for (I #i = Expression.iterator(); #i.hasNext(); ) {
          {VariableModifier} TargetType Identifier =
              (TargetType) #i.next();
          Statement
    }
    

    Rewriting the enhanched for loop with Iterator

    for (String text : text) {...}
    

    becomes

    for (Iterator it = text.iterator(); it.hasNext(); ) {
        String text = it.next();
    }
    

    Then, quoting example 6.4.1 of the JLS:

    A similar restriction on shadowing of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables. Related considerations make restrictions on shadowing of local variables by members of nested classes, or on shadowing of local variables by local variables declared within nested classes unattractive as well.

    As such, there is no compile-time error here because no restriction is made when shadowing a member variable by a local variable, which is the case here: the local variable String text is shadowing the member variable List text.

提交回复
热议问题