且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

变量应该是最终的内部监听器

更新时间:2022-12-27 11:45:20

这是因为你使用的是匿名内部类。
会发生什么,编译器会为您创建类。它将其称为您的外部类,并添加 $ 和数字,例如 $ $ 2 等。

It is because you are using anonymous inner class. What happens is that compiler creates class for you. It calls it as your outer class and adds $ and number, e.g. $, $2 etc.

该类有参考外部类自动初始化,因此它的实例可以使用外部类的方法和字段。

The class has reference to outer class initialized automatically, so its instance can use methods and fields of outer class.

但你的课程是匿名的。它定义了内部方法,可以使用在此匿名类之前定义的内部变量。问题是它怎么能这样做?实际上,您无法参考运行方法的实例来访问其变量。答案是从匿名内部类引用的所有方法变量都被复制到匿名内部类。因此,变量必须是最终的:否则有人可以从外部类更改它们的值,并且更改将不会在内部类中可见。

But your class is anonymous. It kind of defined inside method and can use its internal variables defined before this anonymous class. The question is "how can it do it?" Really, you cannot refer to "instance of running method" to access its variables. The answer is that all method variables referenced from anonymous inner class are copied to the anonymous inner class . Therefore the variables are required to be final: otherwise somebody can change their values from the outer class and the changes will not be visible into the inner class.