假设我们有一个类名 Home。 Home.this 和 Home.class 有什么区别?它们指的是什么?
最佳答案
Home.this
Home.this
引用 Home
类的当前实例。
这个表达式的正式术语似乎是 Qualified this ,如 Java 语言规范的第 15.8.4 节中所引用。
在一个简单的类中,说 Home.this
和 this
是等价的。此表达式仅在存在内部类且需要引用封闭类的情况下使用。
例如:
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
将返回 Home
类的表示形式为 Class
对象。
这个表达式的正式术语是class literal ,如 Java 语言规范的第 15.8.2 节中所引用。
在大多数情况下,当使用 reflection 时会使用此表达式。 ,并且需要一种方法来引用类本身而不是类的实例。
关于java - java中.this和.class的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3434041/