Reputation: 683
I have a couple of questions about instances of the class Class
1) Do I understand correctly that say for the class Dog there is only one instance of the class Class. In other words, given the following lines
Dog dog1 = new Dog();
Dog dog2 = new Dog();
Class dog1Class = dog1.getClass();
Class dog2Class = dog2.getClass();
Class dogClass = Dog.class;
there is only one instance of the class Class - Class<Dog>
.
If you compare these references with ==, you get that they are the same object.
The question exactly is, will getClass and static .class always return the same instance during one execution of a main method?
2) When exactly are these instances created?
Upvotes: 6
Views: 198
Reputation: 19682
There is only one Class
instance representing a class; you can rest assured that it is the same instance, no matter how you get it.
For example, a static synchronized method uses that exact instance for locking; apparently it won't work if there are multiple instances. see http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.3.6
Upvotes: 1
Reputation: 213311
will getClass and static .class always return the same instance
No, not exactly. dog.getClass()
method returns the runtime type of dog.
Consider the following classes:
class Animal { }
class Dog extends Animal { }
And then in main method:
Animal dog = new Dog();
System.out.println(dog.getClass()); // Prints class Dog
System.out.println(Animal.class); // Prints class Animal
When exactly are these instances created?
When the class is first loaded by JVM. From documentation of Class:
Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
For detailed study:
Upvotes: 5