问题描述
假设我们有一个班级名称Home。 Home.this 和 Home.class 之间有什么区别?他们指的是什么?
Let's say we have a class name Home. What is the difference between Home.this and Home.class? What do they refer to?
推荐答案
Home.this
Home.this
指的是 Home
类的当前实例。
Home.this
refers to the current instance of the Home
class.
此表达式的正式用语似乎是,如Java语言规范第15.8.4节所述。
The formal term for this expression appears to be the Qualified this, as referenced in Section 15.8.4 of the Java Language Specification.
在一个简单的类中,说 Home.this
和此
将是等效的。此表达式仅用于存在内部类的情况,并且需要引用封闭类。
In a simple class, saying Home.this
and this
will be equivalent. This expression is only used in cases where there is an inner class, and one needs to refer to the enclosing class.
例如:
class Hello {
class World {
public void doSomething() {
Hello.this.doAnotherThing();
// Here, "this" alone would refer to the instance of
// the World class, so one needs to specify that the
// instance of the Hello class is what is being
// referred to.
}
}
public void doAnotherThing() {
}
}
Home.class
Home.class
将 object。
Home.class
will return the representation of the Home
class as a Class
object.
这个表达式的正式术语是,如Java语言规范的第15.8.2节所述。
The formal term for this expression is the class literal, as referenced in Section 15.8.2 of the Java Language Specification.
在大多数情况下,当使用,需要一种方法来引用类本身而不是类的实例。
In most cases, this expression is used when one is using reflection, and needs a way to refer to the class itself rather than an instance of the class.
这篇关于java中.this和.class的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!