【问题标题】:Meaning of .this and .class in javajava中.this和.class的含义
【发布时间】:2010-08-08 10:58:21
【问题描述】:

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

【问题讨论】:

    标签: java


    【解决方案1】:

    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 时会使用此表达式,并且需要一种方法来引用类本身而不是类的实例。

    【讨论】:

    • 在 C# 中也有类似的方法吗?
    • @MiladIrannejad 不像 NestingClass.this。见stackoverflow.com/a/185144/1986241
    • Android 编程中的MainActivity.this 怎么样?
    • @nn0p android 基于 Java。所以Java的基本概念也适用于Android。以上答案也适用于MainActivity.this
    【解决方案2】:

    Home.class 返回对应于类Homejava.lang.Class<Home> 的实例。这个对象允许你反射类(找出它有哪些方法和变量,它的父类是什么等)并创建类的实例。

    Home.this 仅在您位于 Home 的嵌套类中时才有意义。这里Home.this会返回嵌套类的对象嵌套在其中的Home类的对象。

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 2023-03-17
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多