Anatomy of a Class Loader

When the Java virtual machine needs access to a particular class, it is up to a class loader to provide the class. The class loader goes through the following steps to load and define a class:

  1. If the class loader has already loaded this class, it should find the previously defined class object and return that object immediately.

  2. The security manager is consulted to see if this program is allowed to access the class in question. If it is not, a security exception is thrown. This step may be considered optional.

  3. Otherwise, an internal class loader is consulted to attempt to load the class from the CLASSPATH. If that succeeds, the class loader returns. This ensures that classes within the Java API will not be superseded by classes loaded from the network (or other location).

    The way this is done varies between 1.1 and 1.2.[7] In 1.1, there is a single method (the findSystemClass() method) that handles this step. In 1.2, a class loader must delegate to another class loader to find classes that are on the CLASSPATH and call the findSystemClass() method to find classes that are in the core API.

  4. The security manager is consulted to see if this program is allowed to create the class in question. If it is not, a security exception is thrown. This step may be considered optional.

  5. The class file is read into an array of bytes. The mechanism by which the class loader reads the file and creates the byte array will vary depending on the class loader (which, after all, ...

Get Java Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.