简体   繁体   English

匿名内部类在访问其原语等时是否始终捕获对“this”(外部)对象的引用?

[英]Does an anonymous inner class always capture a reference to “this” (outer) object when accessing its primitives etc.?

If I have 如果我有

[EDIT: added the type definition for "Inner"] [编辑:添加“内部”的类型定义]

interface Inner{
    public void execute();
}

class Outer{
    int outerInt;
    public void hello(){
        Inner inner = new Inner(){
            public void execute(){
                outerInt=5;
            }
        }

        //later
        inner.execute();
    }
}

will the call to inner.execute() set the outerInt variable of that particular Outer object to 5 , wherever it is called from, and for as long as that Inner object exists? inner.execute()的调用是否会将该特定 Outer对象的outerInt变量设置为5 ,无论它在何处被调用,只要该Inner对象存在? Or will it just change a copy of the outerInt variable and not affect the original Outer object? 或者它只是更改outerInt变量的副本而不影响原始的Outer对象?

This will capture and modify the outer this . 这将捕获并修改外this

See the spec 请参阅规格

To answer your newly clarified question (from the comment to my other answer): 回答你新澄清的问题(从评论到我的其他答案):

Yes . 是的
All inner and local classes will have a reference to their parent's this , even if they never use it. 所有内部和局部类将有他们的父母的一个参考this ,即使他们从来没有使用它。
Demo . 演示

This is not necessarily true. 这不一定是真的。 You didn't show is the class declaration for Inner. 你没有展示的是Inner的类声明。 If Inner has a field called outerInt, then that one will be modified. 如果Inner有一个名为outerInt的字段,那么将修改该字段。 Otherwise Outer's outerInt will. 否则外面的外部会。 If you run: 如果您运行:

public class Outer {

    int outerInt = 0;

    public void hello() {
        Inner inner = new Inner() {
            @Override
            public void execute() {
                outerInt = 5;
            }
        };

        // later
        inner.execute();
        System.out.println(outerInt);
    }

    public static void main(String[] args) {
        Outer o = new Outer();
        o.hello();
    }
}

class Inner {
    int outerInt;

    public void execute() {

    }
}

You will get 0, not 5. 你会得到0而不是5。

But by commenting out outerInt in Inner, then you get 5 但是通过评论Inner的outerInt,你得到5

Yes it does. 是的,它确实。 But if you have a need to use outer class's instance, eg passing to some method, you have to say Outer.this. 但是如果你需要使用外部类的实例,例如传递给某个方法,你必须说Outer.this。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM