When we create an object using new operator, does it use the actual .class file to create an object in java

rematnarab :

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?

Kaushal :

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)

  1. Call findLoadedClass to see if already loaded the class.
  2. If haven't loaded the class, get the bytes using findClass (overridden by class loader implementations).
  3. If raw bytes found, call defineClass to turn them into a Class object. (example in AppClassLoader)
  4. If the class resolved, call resolveClass to resolve the Class object.
  5. 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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=470905&siteId=1