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

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

问题描述

据我了解,内部匿名类(但在其外部声明)中使用的任何变量实际上都传递其值的副本.还要求将这些外部变量声明为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?

推荐答案

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

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天全站免登陆