所有最终变量都是由匿名类捕获的吗? [英] Are all final variables captured by anonymous classes?

查看:175
本文介绍了所有最终变量都是由匿名类捕获的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我知道答案,但是我在一小时左右的搜索后找不到任何确认。

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

在此代码中:

public class Outer {

    // other code

    private void method1() {
        final SomeObject obj1 = new SomeObject(...);
        final SomeObject obj2 = new SomeObject(...);
        someManager.registerCallback(new SomeCallbackClass() {
            @Override
            public void onEvent() {
                 System.out.println(obj1.getName());
            }
        });
    }
}

假设 registerCallback 将其参数保存在某处,以便匿名子类的对象将存活一段时间。显然,此对象必须保持对 obj1 的引用,以便 onEvent 在调用它时可以正常工作。

Assume that registerCallback saves its parameter somewhere, so that the object of the anonymous subclass will live for a while. Obviously this object has to maintain a reference to obj1 so that onEvent will work if it is called.

但鉴于该对象不使用 obj2 ,它是否仍然保持对 obj2 <的引用/ code>,这样,当对象存在时, obj2 无法进行垃圾收集?我的印象是所有可见最终(或实际上是最终的)局部变量和参数被捕获,因此不能被GC作为只要对象还活着,但我找不到任何说明这种或那种的东西。

But given that the object doesn't use obj2, does it still maintain a reference to obj2, so that obj2 can't be garbage-collected while the object lives? I was under the impression that all visible final (or effectively final) local variables and parameters were captured and thus couldn't be GC'ed as long as the object was alive, but I can't find anything that says one way or the other.

它是依赖于实现的吗?

JLS中是否有一个部分可以解答这个问题?我无法在那里找到答案。

Is there a section in the JLS that answers this? I wasn't able to find the answer there.

推荐答案

关于匿名类应如何捕获语言规范几乎没有什么可说的来自其封闭范围的变量。

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

我能找到的语言规范中唯一特别相关的部分是 JLS Sec 8.1.3

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


使用但未在内部类中声明的任何局部变量,形式参数或异常参数必须声明为final或者是有效的final(§4.12.4),或者是编译时错误发生在尝试使用的地方。)

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.)

匿名类是内部类

它没有指定匿名类应捕获哪些变量或捕获方式应该实现。

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.

这篇关于所有最终变量都是由匿名类捕获的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆