Java:类.this
我有一个看起来像这样的 Java 程序。
public class LocalScreen {
public void onMake() {
aFuncCall(LocalScreen.this, oneString, twoString);
}
}
LocalScreen.this
在 aFuncCall
中意味着什么?
I have a Java program that looks like this.
public class LocalScreen {
public void onMake() {
aFuncCall(LocalScreen.this, oneString, twoString);
}
}
What does LocalScreen.this
means in aFuncCall
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
LocalScreen.this
引用封闭类的this
。这个例子应该解释一下:
输出:
LocalScreen.this
refers tothis
of the enclosing class.This example should explain it:
Output:
它表示外部
LocalScreen
类的this
实例。编写不带限定符的
this
将返回 内部类。It means the
this
instance of the outerLocalScreen
class.Writing
this
without a qualifier will return the instance of the inner class that the call is inside of.编译器接受代码并用它做类似的事情:
如您所见,当编译器接受内部类时,它将其转换为外部类(这是很久以前做出的设计决策,因此虚拟机不需要进行更改以理解内部类)。
当创建非静态内部类时,它需要对父类的引用,以便它可以调用外部类的方法/访问变量。
内部类中的 this 不是正确的类型,您需要访问外部类才能获得调用 onMake 方法的正确类型。
The compiler takes the code and does something like this with it:
As you can see, when the compiler takes an inner class it converts it to an outer class (this was a design decision made a LONG time ago so that VMs did not need to be changed to understand inner classes).
When a non-static inner class is made it needs a reference to the parent so that it can call methods/access variables of the outer class.
The this inside of what was the inner class is not the proper type, you need to gain access to the outer class to get the right type for calling the onMake method.
Class.this
允许访问外部类的实例。请参阅以下示例。然后你就会得到。
Class.this
allows access to instance of the outer class. See the following example.Then you will get.
我知道你的困惑是什么。我刚才遇到了这个问题,应该有特殊的场景来区分它们。
hashcode( .## ) 测试来查看新 THIS 操作中
THIS.this
和this
之间的差异您可以通过scala 控制台中的
:
THIS.this
总是指向由 val x 引用的外部 THIS 类,但是this
超出了匿名 new 操作的范围。I know what is your confusion.I am encounter the problem just now, it should have special scene to distinguish them.
You can see the diff between
THIS.this
andthis
in new THIS operation by hashcode( .## )test in scala console :
THIS.this
always point to outer THIS class which is refer by val x,butthis
is beyond to anonymous new operation.