Reputation: 212
There are 2 ways to get a class's Class
object.
Statically:
Class cls = Object.class;
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?
Upvotes: 14
Views: 1251
Reputation: 121998
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 tokenclass
.A class literal evaluates to the
Class
object for the named type (or forvoid
) as defined by the defining class loader (§12.2) of the class of the current instance.
Upvotes: 12
Reputation: 31
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
Upvotes: 0