Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is .class defined in Java? (Is it a variable or what?)

Tags:

java

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?

like image 912
Pavankant Avatar asked Jan 22 '18 06:01

Pavankant


People also ask

Is class A variable 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 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.

Where are class variables defined?

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.

Is a class A variable?

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).


1 Answers

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.

like image 118
Suresh Atta Avatar answered Sep 20 '22 13:09

Suresh Atta