I am confused about a subject and can not find it on the web.
As I understand it, when the program starts the class loader loads the .class
files and store them in the memory as objects with the type Class
.
My question is when we use:
Test test = new Test();
Is the new object created using .class
file, or using the Class
object already in the memory?
Once a class is loaded into a JVM, the same class will not be loaded again for same class loader. New instance will be created from class object in memory (for same class loader).
Steps at high level (copied from https://www.ibm.com/developerworks/java/tutorials/j-classloader/j-classloader.html)
- Call findLoadedClass to see if already loaded the class.
- If haven't loaded the class, get the bytes using findClass (overridden by class loader implementations).
- If raw bytes found, call defineClass to turn them into a Class object. (example in AppClassLoader)
- If the class resolved, call resolveClass to resolve the Class object.
If still don't have a class, throw a ClassNotFoundException.
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded Class c = findLoadedClass(name); if (c == null) { try { if (parent != null) { c = parent.loadClass(name, false); } else { c = findBootstrapClass0(name); } } catch (ClassNotFoundException e) { // If still not found, then invoke findClass in order // to find the class. c = findClass(name); } } if (resolve) { resolveClass(c); } return c; }
Example all of following will print same hashCode and refers to same Test.class
Test test1 = new Test();
Test test2 = new Test();
System.out.println(test2.getClass().hashCode());
System.out.println(test1.getClass().hashCode());
System.out.println(Test.class.hashCode());
For more details http://www.onjava.com/pub/a/onjava/2005/01/26/classloading.html?page=1