gpt4 book ai didi

java - java中.this和.class的含义

转载 作者:IT老高 更新时间:2023-10-28 20:53:20 25 4
gpt4 key购买 nike

假设我们有一个类名 Home。 Home.thisHome.class 有什么区别?它们指的是什么?

最佳答案

Home.this

Home.this 引用 Home 类的当前实例。

这个表达式的正式术语似乎是 Qualified this ,如 Java 语言规范的第 15.8.4 节中所引用。

在一个简单的类中,说 Home.thisthis 是等价的。此表达式仅在存在内部类且需要引用封闭类的情况下使用。

例如:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com