14

There are 2 ways to get a class's Class object.

  1. Statically:

    Class cls = Object.class;
    
  2. From an instance:

    Object ob = new Object();  
    Class cls = ob.getClass();
    

Now my question is getClass() is a method present in the Object class, but what is .class? Is it a variable? If so then where is it defined in Java?

Boann
  • 48,794
  • 16
  • 117
  • 146
Pavankant
  • 212
  • 1
  • 12

2 Answers2

12

That's implemented internally and called a class literal which is handled by the JVM.

The Java Language Specification specifically mentions the term "token" for it.

So .class is more than a variable, to be frank it is not a variable at all. At a broader level you can consider it as a keyword or token.

https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.8.2

A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.

A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader (§12.2) of the class of the current instance.

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 2
    Just a side note, `Object.getClass()` is defined with the `native` keyword, so it's also handled by JVM. Both ways probably share the same native implementation. – Jai Jan 22 '18 at 06:54
0

That information resides in the class 'file', although classes need not have a physical .class file in the file system. The JVM takes care of making it available from the class definition, as the other answer states.

See also: https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html

Marc.S
  • 31
  • 7