When does object pointed by 'Example.class' come into existence?

You are confusing artifacts of the Java programming language with items of the constant pool of a class file holding Java byte code.

Class literals of the form type.class, as well as an access to the length of an array of the form array.length may look like a member access in the source code but have nothing to do with real class members.

E.g. when you write array.length, it will get compiled to a bytecode instruction arraylength dedicated to retrieve the length of an array at runtime without actually specifying how a JVM remembers lengths of arrays. That’s implementation dependent.

A class literal is more complicated. E.g. when you write int.class, there is nothing to query. Instead, the compiler knows that it has to read the static field Integer.TYPE to get the runtime value and that’s how this class literal gets compiled, as a field access to Integer.TYPE. In contrast, class literals of reference types are compiled using an ldc instruction pointing to a constant pool entry which has nothing to to with fields.

The constant pool of a class does not contain Java objects in the first place. It contains linkage information. Some entries might get associated with a Java runtime instance on their first use but the way it works is intentionally unspecified. That’s up to the JVM. These entries serve different purposes, i.e. a Class entry can be used to specify a super class, an implemented interface or a class, whose member is accessed by a method invocation or field access.

That’s why your Example class file contains such a Class entry. It’s there because the class uses it to describe itself. Even if there is no class literal Example.class at all. Consequently, a Class instance describing the class Example is create when the class is loaded. A ClassLoader remembers all loaded classes and they will be used when the same name is resolved using the same loader.

Note that when another class contains a class literal of the form Example.class, it will have it’s own Class entry for that class within its own constant pool. The runtime evaluation of the class literal may trigger the loading and hence creating of the Class instance when it has not been loaded before. Otherwise, it gets resolved to the already loaded class via the class loader.

Browse More Popular Posts

Leave a Comment