According to the Java 8 Language Spec §15.8.2 (quote):
[...]
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.[...]
Mainly, 'the Class
object' insinuates that this is or should be a singleton. Also §12.2 says:
[...]
Well-behaved class loaders maintain these properties:
- Given the same name, a good class loader should always return the same class object.
[...]
In fact, using Java 8*, the following** prints true
and true
:
class Main {
public static void main(String[] args) {
Main main1 = new Main();
Main main2 = new Main();
System.out.println(main1.getClass().equals(main2.getClass()));
System.out.println(main1.getClass() == main2.getClass());
}
}
Is the class loader always 'well-behaved' and why (not)? In other words: are Class
instances singleton? The other way around: can a Class
of the same type be a different instance?
Notes: I do not refer to the singleton pattern here. However, if the Class
implementation follows that pattern, that would be interesting. As a side-step, but by no means the main question: because the singleton pattern's legitimate uses are point of debate, would Java's Class
be a good candidate to apply the singleton pattern to?
*:
$ java -version
openjdk version "1.8.0_262"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_262-b10)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.262-b10, mixed mode)
**: my IDE even warns me that the printed expressions are always true
.