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?
Class/Static VariablesClass variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
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.
Class variables are declared inside the class definition but outside any of the instance methods and constructors. It is gets created when an instance of the class is created. It is created when the program begins to execute.
In class-based, object-oriented programming, a class variable is a variable defined in a class of which a single copy exists, regardless of how many instances of the class exist. A class variable is not an instance variable. It is a special type of class attribute (or class property, field, or data member).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With