V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
JasonLaw
V2EX  ›  Java

关于“ Java - Why are only final variables accessible in anonymous class? - Stack Overflow”的疑惑

  •  
  •   JasonLaw · 2020-09-29 15:28:36 +08:00 · 1530 次点击
    这是一个创建于 1276 天前的主题,其中的信息可能已经有所发展或是发生改变。

    java - Why are only final variables accessible in anonymous class? - Stack Overflow中,Jon Skeet 说了这么一段话:

    When you create an instance of an anonymous inner class, any variables which are used within that class have their values copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does... (When C# captures a variable in an anonymous function, it really captures the variable - the closure can update the variable in a way which is seen by the main body of the method, and vice versa.)

    我对“This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does...”的理解是:如果要实现 full closures support,那么就需要产生一个共享的数据结构用来包含外部方法和内部类所共同访问的变量,这样两者都是使用同一个数据源,那么一方对变量的改变就会对另一方可见,类似Ivan Dubrov 所说的

    我不肯定我的理解是否正确,所以我想看一下大家对这句话的理解。

    5 条回复    2020-09-30 11:03:52 +08:00
    mightofcode
        1
    mightofcode  
       2020-09-29 17:48:09 +08:00
    我觉得你的理解没错
    lxk11153
        2
    lxk11153  
       2020-09-29 18:20:36 +08:00
    好像有点道理 [doge]
    javlib
        3
    javlib  
       2020-09-29 20:44:50 +08:00 via Android
    那么以后会不会改成非 final 变量也能在闭包使用呢?就像现在的 c#
    JasonLaw
        4
    JasonLaw  
    OP
       2020-09-29 21:11:12 +08:00 via iPhone
    @javlib 不知道🤣
    yazinnnn
        5
    yazinnnn  
       2020-09-30 11:03:52 +08:00
    闭包是代码块异地执行的手段,每个代码块实例所包含的变量(包括外部变量)放在同一个上下文里。。每个闭包过程实例有独立的生命周期

    如果你的某个代码块没有回收,那这个上下文里的相关变量也不会回收
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1384 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 74ms · UTC 17:32 · PVG 01:32 · LAX 10:32 · JFK 13:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.