修改匿名内部类中的外部变量 [英] Modifying an outer variable within an anonymous inner class

查看:79
本文介绍了修改匿名内部类中的外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,内部匿名类中使用的任何变量(但在其外部声明)实际上都传递了其值的副本.还有一个要求是将这些外部变量声明为final,这显然意味着这些变量不应该被修改.

As I understand it, any variables used within an inner anonymous class (but declared outside of it) are actually passed a copy of their values. There is also a requirement that these outer variables be declared as final, which obviously means that these variables are not meant to be modified.

但是有什么办法可以解决这个问题吗?我的匿名内部类实际上可以修改一些变量或对象,然后我可以在我的代码中使用它们(匿名类之外)?或者在匿名类之外不会看到修改?

But is there any kind of work-around to this? Can my anonymous inner class actually modify some variable or object, which I could then use later on in my code (outside of the anonymous class)? Or would the modifications not be seen outside of the anonymous class?

推荐答案

您所指的行为仅适用于局部变量或方法/catch 参数.您可以很好地访问并可能修改实例成员

The behavior you are referring to applies only to local variables or method/catch parameters. You can access and, potentially, modify instance members just fine

public class Example {

    public void method() {
        String localFoo = "local";
        new Object() {
            public void bar() {
                foo = "bar"; // yup
                System.out.println(localFoo); // sure
                localFoo = "bar"; // nope
            }
        };        
    }

    private String foo = "foo";
}

匿名Object 内部类复制localFoo 的值以在println(..) 调用中使用.然而,对于 foo,它实际上是复制"对 Example 实例的引用并引用它的 foo 字段.

The anonymous Object inner class copies the value of localFoo for use within the println(..) invocation. However, for foo, it's actually "copying" the reference to the Example instance and referencing its foo field.

实际上相当于

Example.this.foo = "bar";

这篇关于修改匿名内部类中的外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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