3

In Java you can write the following code:

Class<?> stringClass = String.class;

The run-time will assign a reference to a Class instance represents the type java.lang.String class.

My questions are:

  1. Is it guaranteed by the JVM that a Class instance is a singleton per Java type?
  2. If the answer to #1 is true - when the Class instance is being created? (- calling getClass() or Type.class or maybe when the Class loader is loading a Java type at the first time.)
  3. What happens under the hood when invoking Type.class. I am asking since there is no static member called class in the code of-course.
Oz Molaim
  • 2,016
  • 4
  • 20
  • 29

2 Answers2

1
  1. According to this question, Class objects per type are unique, given that you have only one ClassLoader. Different ClassLoaders can yield different Class objects for the same class definition.
  2. The Class objects are created when the class is loaded by a ClassLoader, usually when the class is first referenced.
  3. According to the Java Language Specification, Section 15.8.2, Type.class is a class literal, so nothing is being invoked; the class literal refers to the Class object.

Quoting the JLS from the section linked above:

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.

and

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.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
1

It appears that the expression Foo.class is compiled to a simple lookup of constant pool, at least on javac7. So Foo.class is probably loaded when this class is loaded.

I remember that's not the case in older versions of Java; Foo.class was compiled into something like Class.forName("Foo") and the loading was rather lazy and on demand.

ZhongYu
  • 19,446
  • 5
  • 33
  • 61