Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of .this and .class in java

Tags:

java

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

like image 341
Gooner Avatar asked Aug 08 '10 10:08

Gooner


People also ask

What does .class mean in Java?

What Does Class Mean? A class — in the context of Java — is a template used to create objects and to define object data types and methods. Classes are categories, and objects are items within each category. All class objects should have the basic class properties.

What does .this mean in Java?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

What does .class expected mean?

'(' expected or ')' expected This error means that you forgot a left or right parenthesis in your code. If you look at the full error statement, it will tell you where in your code you should check. Remember that for every ( you need one ).


2 Answers

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.

like image 141
coobird Avatar answered Oct 07 '22 06:10

coobird


Home.class returns 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.this is only meaningful if you're inside a nested class of Home. Here Home.this will return the object of class Home that the object of the nested class is nested in.

like image 25
sepp2k Avatar answered Oct 07 '22 07:10

sepp2k