java java中.this和.class的含义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3434041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Meaning of .this and .class in java
提问by Gooner
Let's say we have a class name Home. What is the difference between Home.thisand Home.class? What do they refer to?
假设我们有一个类名 Home。是什么区别Home.this和Home.class?他们指的是什么?
回答by coobird
Home.this
首页.this
Home.thisrefers to the current instance of the Homeclass.
Home.this指Home类的当前实例。
The formal term for this expression appears to be the Qualified this, as referenced in Section 15.8.4 of the Java Language Specification.
此表达式的正式术语似乎是Qualified this,如 Java 语言规范的第 15.8.4 节中所引用。
In a simple class, saying Home.thisand thiswill be equivalent. This expression is only used in cases where there is an inner class, and one needs to refer to the enclosing class.
在一个简单的类中,sayHome.this和thiswill 是等价的。此表达式仅用于存在内部类的情况,并且需要引用封闭类。
For example:
例如:
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.classwill return the representation of the Homeclass as a Classobject.
Home.class将Home类的表示作为Class对象返回。
The formal term for this expression is the class literal, as referenced in Section 15.8.2 of the Java Language Specification.
该表达式的正式术语是类文字,如 Java 语言规范的第 15.8.2 节中所引用。
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.
在大多数情况下,这个表达式在使用反射时使用,并且需要一种方法来引用类本身而不是类的实例。
回答by sepp2k
Home.classreturns the instance of java.lang.Class<Home>that corresponds to the class Home. This object allows you to reflect over the class (find out which methods and variables it has, what its parent class is etc.) and to create instances of the class.
Home.class返回java.lang.Class<Home>对应于类的实例Home。该对象允许您反映该类(找出它具有哪些方法和变量,它的父类是什么等)并创建该类的实例。
Home.thisis only meaningful if you're inside a nested class of Home. Here Home.thiswill return the object of class Homethat the object of the nested class is nested in.
Home.this仅当您在 Home 的嵌套类中时才有意义。这里Home.this将返回Home嵌套类的对象所嵌套的类的对象。

