【发布时间】:2010-08-08 10:58:21
【问题描述】:
假设我们有一个类名 Home。 Home.this 和 Home.class 有什么区别?它们指的是什么?
【问题讨论】:
标签: java
假设我们有一个类名 Home。 Home.this 和 Home.class 有什么区别?它们指的是什么?
【问题讨论】:
标签: java
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 时会使用此表达式,并且需要一种方法来引用类本身而不是类的实例。
【讨论】:
MainActivity.this 怎么样?
MainActivity.this
Home.class 返回对应于类Home 的java.lang.Class<Home> 的实例。这个对象允许你反射类(找出它有哪些方法和变量,它的父类是什么等)并创建类的实例。
Home.this 仅在您位于 Home 的嵌套类中时才有意义。这里Home.this会返回嵌套类的对象嵌套在其中的Home类的对象。
【讨论】: