开发者

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

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开发者_如何学Go how to solve it (just declare a "me" variable), but I need to know why I can't use <Class>.this?


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.


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜