Aniket Thakur
Aniket Thakur

Reputation: 68935

Where is ObjectClass.class variable defined/initialized?

Consider 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 compile time Class object. Looking at the Test.class syntax it looks like the variable class is of type java.lang.Class and is static and public. My question is where is this variable defined? It is not present in Test class (because I don't declare it) neither it is in the java.lang.Object class.

I saw an analogous 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 an object.

So my question is where is this public & static class variable defined?(Please correct me if I have mistaken) Is it again some native implementation? This is set at compile time and being static needs no class instance to be created. So if even this is some native implementation is it initialized by registerNatives() method in java.lang.Object?

Upvotes: 4

Views: 86

Answers (3)

arshajii
arshajii

Reputation: 129507

These are called class literals and are defined by the language itself as per JLS §15.8.2 (there is no "class member"):

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.

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

The type of 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 boxing conversion (§5.1.7).

The type of void.class (§8.4.5) is Class<Void>.

One indication that these constructs are intrinsically built into the language is that they even work with primitives!

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

Upvotes: 5

AlexR
AlexR

Reputation: 115328

Your assumption that class is a static field of class Class is not exact. Assume that this is correct. In this case the value of this field will be exactly the same for all classes that is wrong.

Although MyClass.class syntactically looks like access to static field it is just a special syntax of language. Think about this as a kind of operator.

Probably JVM creates some kind of synthetic class that wraps real class and has such field but it is just an assumption about internal representation of classes in JVM.

Upvotes: 0

Jimmy T.
Jimmy T.

Reputation: 4190

class is not normal static variable. It's a language construct which is replaced at compilation time.

Because class is a keyword it wouldn't even be possible to declare a variable with that name.

Upvotes: 1

Related Questions