问题
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