Are all final variables captured by anonymous classes?

后端 未结 4 1195
北恋
北恋 2021-02-13 00:03

I thought I knew the answer to this, but I can\'t find any confirmation after an hour or so of searching.

In this code:

public class Outer {

    // othe         


        
4条回答
  •  有刺的猬
    2021-02-13 00:36

    The language spec has very little to say about how anonymous classes should capture variables from their enclosing scope.

    The only especially relevant section of the language spec that I can find is JLS Sec 8.1.3:

    Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.)

    (Anonymous classes are inner classes)

    It does not specify anything about which variables the anonymous class should capture, or how that capturing should be implemented.

    I think it is reasonable to infer from this that implementations need not capture variables that aren't referenced in the inner class; but it doesn't say they can't.

提交回复
热议问题