Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's say we have a class name Home. What is the difference between Home.this and Home.class? What do they refer to?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
131 views
Welcome To Ask or Share your Answers For Others

1 Answer

Home.this

Home.this refers to the current instance of the Home class.

The formal term for this expression appears to be the Qualified this, as referenced in Section 15.8.4 of the Java Language Specification.

In a simple class, saying Home.this and this will be equivalent. This expression is only used in cases where there is an inner class, and one needs to refer to the enclosing class.

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.class will return the representation of the Home class as a Class object.

The formal term for this expression is the class literal, as referenced in Section 15.8.2 of the Java Language Specification.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...