java如何实现内部类闭包? [英] How does java implement inner class closures?

查看:134
本文介绍了java如何实现内部类闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,匿名内部类可以引用其局部范围内的变量:

  public class A {
public void method(){
final int i = 0;

doStuff(新动作(){
公共无效doAction(){
Console.printf(我); //或任何
}
} );
}
}

我的问题是这是如何实现的?如何 I 获得的匿名内部 doAction 实施,为什么它必须是最后


解决方案

,编译器会自动为您的匿名内部类的构造,并通过您的



构造函数将此值保存在类变量(字段)中,也称为 i ,它将在闭包内使用。



为什么它必须是final?好,让我们来探讨一下不是这样的情况:

  public class A {
public void method
int i = 0; //注意:这是错误的代码

doStuff(新动作(){
公共无效doAction(){
Console.printf(我); //或任何
}
});

i = 4; // A
// B
i = 5; // C
}
}

$ c> i 也需要更改,我们假设这是可能的:它需要引用假设在情境B中, Action 的实例是Garbage-C



现在在情况C:它需要一个 Action 的实例来更新它的类变量,是GCed。它需要知道它的GCed,但这是很困难的。



为了保持VM的实现更简单,Java语言设计者说,它应该是最终使得VM不需要一种方式来检查对象是否走了,并且保证该变量不被修改,并且VM或编译器不必保持对匿名内部对象内的变量的所有使用的引用,类及其实例。


In Java an anonymous inner class can refer to variables in it's local scope:

public class A {
    public void method() {
        final int i = 0;

        doStuff(new Action() {
            public void doAction() {
                Console.printf(i);   // or whatever
            }
        });
    }
}

My question is how is this actually implemented? How does i get to the anonymous inner doAction implementation, and why does it have to be final?

解决方案

The compiler automatically generates a constructor for your anonymous inner-class, and passes your local variable into this constructor.

The constructor saves this value in a class variable (a field), also named i, which will be used inside the "closure".

Why it has to be final? Well let's explore the situation in where it isn't:

public class A {
    public void method() {
        int i = 0; // note: this is WRONG code

        doStuff(new Action() {
            public void doAction() {
                Console.printf(i);   // or whatever
            }
        });

        i = 4; // A
        // B
        i = 5; // C
    }
}

In situation A the field i of Action also needs to be changed, let's assume this is possible: it needs the reference to the Action object.

Assume that in situation B this instance of Action is Garbage-Collected.

Now in situation C: it needs an instance of Action to update it's class variable, but the value is GCed. It needs to "know" it's GCed, but that is difficult.

So to keep the implementation of the VM simpler, the Java language designers have said that it should be final such that the VM doesn't need a way to check whether an object is gone, and guarantee that the variable is not modified, and that the VM or compiler doesn't have to keep reference of all usages of the variable inside anonymous inner-classes and their instances.

这篇关于java如何实现内部类闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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