Search code examples
javaclassloader

Java: Where is the memory allocated for the physical bytes of a class when loaded by a ClassLoader?


I have constructed a tiny custom class loader in a dummy application in order to understand how dynamic class loading works. For this question, I don't need to go into details about what it does other than to mention that it instantiates two different instances of my class loader and has each one load different classes, in order that I can satisfy myself by confirming a "ClassNotFoundException" from one of the class loader instances when only the other has loaded a particular class.

However, I have a question that can be easily expressed by the following, hopefully self-explanatory line of code.

        Class clazz = myClassLoader.loadClass(theClazz);

This line of code causes my custom class loader to LOAD the class bytes into memory, and to return an instance of a Class object for that class.

My question is this: Where are the physical bytes of memory for the loaded class located (i.e., the contents of the .class file)? Are they stored inside the ClassLoader object, or are they stored inside the Class object (whereupon the ClassLoader object merely contains an internal reference to this Class object) - or somewhere else entirely?


Solution

  • The classloader object has a Collection of all classes it has loaded.

    If the same physical class is loaded by 2 different class laoders, the bytes of that class are two times in memeory. The two classes behave like different types. They are not compatible to each other! Where the bytes are stored is not really relevant, I wonder why you want to know that. If you write your own ClassLoader you can "store" them where ever you want. However at some point you will make a call like: ClassLoader.defineClass(String, byte[], int, int). Then the relevant structures in memory inside the VM are created (MethodArea, ConstantPool etc.) as mentioned in other answers.