Why can't I use <Class>.this in anonymous class?

非 Y 不嫁゛ 提交于 2020-01-14 09:07:56

问题


I recently use this code, and realize that in anonymous class, I can't access the instance by .this, like this:

Sprite sprFace = new Sprite() {

    @Override
    protected void onManagedUpdate(float pSecondElapsed) {
        runOnUpdateThread(new Runnable() {

        @Override
        protected void run() {    
            Sprite.this.getParent().detach(Sprite.this); // Here
        }});
    }

};

I know how to solve it (just declare a "me" variable), but I need to know why I can't use <Class>.this?


回答1:


The <Class>.this syntax gives a special way of referring to the object of type <Class>, as opposed to the shadowing type.

In addition, <Class> must be the name of the type you're trying to access. In your case, Sprite is not the actual type of sprFace. Rather, sprFace is an instance of an anonymous subclass of Sprite, thus the syntax is not applicable.




回答2:


The type of the outer object is not Sprite, but rather an anonymous subclass of Sprite and you have no way of naming this anonymous subclass in your code.

In this case you need a name to refer to and therefore an anonymous class will not do the job. You can use a local class instead (which behaves as an anonymous class with a name). In the code block, you can write:

class MySprite extends Sprite {

    @Override
    protected void onManagedUpdate(float pSecondElapsed) {
        runOnUpdateThread(new Runnable() {
            MySprite.this.getParent().detach(MySprite.this); // Here
        });
    }

};

Sprite sprFace = new MySprite();


来源:https://stackoverflow.com/questions/7103087/why-cant-i-use-class-this-in-anonymous-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!