Where is the variable ObjectClass.class defined / initialized?

Consider the sample code below

public class Test { public static void main(String args[]) { Test t = new Test(); Class c2 = Test.class; System.out.println(c2); } } 

Test.class statically evaluates and returns the time of a class object. If you look at the syntax of Test.class , it looks like a class of the variable type java.lang.Class and is static and public . My question is where is this variable defined? It is not in the Test class (because I do not declare it) nor in the java.lang.Object class.

I saw a similar method public final native Class<?> getClass(); . This is present in java.lang.Object and is a native java method . This method returns the runtime class of the object.

So my question is where is this variable public and static class defined? (Please correct me if I am wrong). Is this again some kind of own implementation? This is set at compile time and does not statically require instantiating a class. So, even if this is some kind of built-in implementation, is it initialized with the registerNatives() method in java.lang.Object?

+4
source share
3 answers

They are called class literals and are defined by the language itself according to JLS ยง15.8.2 (there is no class element "):

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

Type C.class , where C is the name of a class, interface, or array type (ยง4.3), Class<C> .

The type p.class , where p is the name of a primitive type (ยง4.2), is Class<B> , where B is the type of an expression of type p after the box conversion (ยง5.1.7).

The type void.class (ยง8.4.5) is equal to Class<Void> .

One of the signs that these constructs are embedded in the language is that they even work with primitives!

 System.out.println(int.class); System.out.println(double.class); // etc. 
+5
source

class not a normal static variable. This is a language construct that is replaced at compile time.

Since class is a keyword, it would not even be possible to declare a variable with this name.

+1
source

Your assumption that class is a static field of class class is not accurate. Suppose this is correct. In this case, the value of this field will be exactly the same for all classes that are incorrect.

Although MyClass.class syntactically looks like accessing a static field, this is just a special language syntax. Think of it as some kind of operator.

The JVM probably creates some kind of synthetic class that wraps the real class and has such a field, but this is just an assumption about the internal representation of the classes in the JVM.

0
source

Source: https://habr.com/ru/post/1501171/


All Articles