Creation of a class or interface C denoted by the name N consists of the construction in the method area of the Java Virtual Machine (§2.5.4) of an implementation-specific internal representation of C. Class or interface creation is triggered by another class or interface D, which references C through its run-time constant pool. Class or interface creation may also be triggered by D invoking methods in certain Java SE platform class libraries (§2.12) such as reflection.
If C is not an array class, it is created by loading a binary representation of C (§4 (The class File Format)) using a class loader. Array classes do not have an external binary representation; they are created by the Java Virtual Machine rather than by a class loader.
There are two kinds of class loaders: the bootstrap class loader supplied by the Java Virtual Machine, and user-defined class loaders. Every user-defined class loader is an instance of a subclass of the abstract class ClassLoader. Applications employ user-defined class loaders in order to extend the manner in which the Java Virtual Machine dynamically loads and thereby creates classes. User-defined class loaders can be used to create classes that originate from user-defined sources. For example, a class could be downloaded across a network, generated on the fly, or extracted from an encrypted file.
A class loader L may create C by defining it directly or by delegating to another class loader. If L creates C directly, we say that L defines C or, equivalently, that L is the defining loader of C.
When one class loader delegates to another class loader, the loader that initiates the loading is not necessarily the same loader that completes the loading and defines the class. If L creates C, either by defining it directly or by delegation, we say that L initiates loading of C or, equivalently, that L is an initiating loader of C.
At run time, a class or interface is determined not by its name alone, but by a pair: its binary name (§4.2.1) and its defining class loader. Each such class or interface belongs to a single run-time package. The run-time package of a class or interface is determined by the package name and defining class loader of the class or interface.
The Java Virtual Machine uses one of three procedures to create class or interface C denoted by N:
-
If
Ndenotes a nonarray class or an interface, one of the two following methods is used to load and thereby create C: -
Otherwise
Ndenotes an array class. An array class is created directly by the Java Virtual Machine (§5.3.3), not by a class loader. However, the defining class loader of D is used in the process of creating array class C.
If an error occurs during class loading, then an instance of a subclass of LinkageError must be thrown at a point in the program that (directly or indirectly) uses the class or interface being loaded.
If the Java Virtual Machine ever attempts to load a class C during verification (§5.4.1) or resolution (§5.4.3) (but not initialization (§5.5)), and the class loader that is used to initiate loading of C throws an instance of ClassNotFoundException, then the Java Virtual Machine must throw an instance of NoClassDefFoundError whose cause is the instance of ClassNotFoundException.
(A subtlety here is that recursive class loading to load superclasses is performed as part of resolution (§5.3.5, step 3). Therefore, a ClassNotFoundException that results from a class loader failing to load a superclass must be wrapped in a NoClassDefFoundError.)
A well-behaved class loader should maintain three properties:
- Given the same name, a good class loader should always return the same
Classobject. - If a class loader
L_1delegates loading of a class C to another loaderL_2, then for any type T that occurs as the direct superclass or a direct superinterface of C, or as the type of a field in C, or as the type of a formal parameter of a method or constructor in C, or as a return type of a method in C,L_1andL_2should return the sameClassobject. - If a user-defined classloader prefetches binary representations of classes and interfaces, or loads a group of related classes together, then it must reflect loading errors only at points in the program where they could have arisen without prefetching or group loading.
We will sometimes represent a class or interface using the notation <N, L_d>, where N denotes the name of the class or interface and L_d denotes the defining loader of the class or interface.
We will also represent a class or interface using the notation N^{L_i}, where N denotes the name of the class or interface and L_i denotes an initiating loader of the class or interface.
5.3.1. Loading Using the Bootstrap Class Loader
The following steps are used to load and thereby create the nonarray class or interface C denoted by N using the bootstrap class loader.
First, the Java Virtual Machine determines whether the bootstrap class loader has already been recorded as an initiating loader of a class or interface denoted by N. If so, this class or interface is C, and no class creation is necessary.
Otherwise, the Java Virtual Machine passes the argument N to an invocation of a method on the bootstrap class loader to search for a purported representation of C in a platform-dependent manner. Typically, a class or interface will be represented using a file in a hierarchical file system, and the name of the class or interface will be encoded in the pathname of the file.
Note that there is no guarantee that a purported representation found is valid or is a representation of C. This phase of loading must detect the following error:
- If no purported representation of C is found, loading throws an instance of
ClassNotFoundException.
Then the Java Virtual Machine attempts to derive a class denoted by N using the bootstrap class loader from the purported representation using the algorithm found in §5.3.5. That class is C.
5.3.2. Loading Using a User-defined Class Loader
The following steps are used to load and thereby create the nonarray class or interface C denoted by N using a user-defined class loader L.
First, the Java Virtual Machine determines whether L has already been recorded as an initiating loader of a class or interface denoted by N. If so, this class or interface is C, and no class creation is necessary.
Otherwise, the Java Virtual Machine invokes loadClass(N) on L. The value returned by the invocation is the created class or interface C. The Java Virtual Machine then records that L is an initiating loader of C (§5.3.4). The remainder of this section describes this process in more detail.
When the loadClass method of the class loader L is invoked with the name N of a class or interface C to be loaded, L must perform one of the following two operations in order to load C:
- The class loader
Lcan create an array of bytes representing C as the bytes of aClassFilestructure (§4.1); it then must invoke the methoddefineClassof classClassLoader. InvokingdefineClasscauses the Java Virtual Machine to derive a class or interface denoted byNusingLfrom the array of bytes using the algorithm found in §5.3.5. - The class loader
Lcan delegate the loading of C to some other class loaderL'. This is accomplished by passing the argumentNdirectly or indirectly to an invocation of a method onL' (typically theloadClassmethod). The result of the invocation is C.
In either (1) or (2), if the class loader L is unable to load a class or interface denoted by N for any reason, it must throw an instance of ClassNotFoundException.
Since JDK release 1.1, Oracle’s Java Virtual Machine implementation has invoked the loadClass method of a class loader in order to cause it to load a class or interface. The argument to loadClass is the name of the class or interface to be loaded. There is also a two-argument version of the loadClass method, where the second argument is a boolean that indicates whether the class or interface is to be linked or not. Only the two-argument version was supplied in JDK release 1.0.2, and Oracle’s Java Virtual Machine implementation relied on it to link the loaded class or interface. From JDK release 1.1 onward, Oracle’s Java Virtual Machine implementation links the class or interface directly, without relying on the class loader.
5.3.3. Creating Array Classes
The following steps are used to create the array class C denoted by N using class loader L. Class loader L may be either the bootstrap class loader or a user-defined class loader.
If L has already been recorded as an initiating loader of an array class with the same component type as N, that class is C, and no array class creation is necessary.
Otherwise, the following steps are performed to create C:
-
If the component type is a
referencetype, the algorithm of this section (§5.3) is applied recursively using class loaderLin order to load and thereby create the component type of C. -
The Java Virtual Machine creates a new array class with the indicated component type and number of dimensions.
If the component type is a
referencetype, C is marked as having been defined by the defining class loader of the component type. Otherwise, C is marked as having been defined by the bootstrap class loader.In any case, the Java Virtual Machine then records that
Lis an initiating loader for C (§5.3.4).If the component type is a
referencetype, the accessibility of the array class is determined by the accessibility of its component type. Otherwise, the accessibility of the array class ispublic.
5.3.4. Loading Constraints
Ensuring type safe linkage in the presence of class loaders requires special care. It is possible that when two different class loaders initiate loading of a class or interface denoted by N, the name N may denote a different class or interface in each loader.
When a class or interface C = <N_1, L_1> makes a symbolic reference to a field or method of another class or interface D = <N_2, L_2>, the symbolic reference includes a descriptor specifying the type of the field, or the return and argument types of the method. It is essential that any type name N mentioned in the field or method descriptor denote the same class or interface when loaded by L_1 and when loaded by L_2.
To ensure this, the Java Virtual Machine imposes loading constraints of the form N^{L_1} = N^{L_2} during preparation (§5.4.2) and resolution (§5.4.3). To enforce these constraints, the Java Virtual Machine will, at certain prescribed times (see §5.3.1, §5.3.2, §5.3.3, and §5.3.5), record that a particular loader is an initiating loader of a particular class. After recording that a loader is an initiating loader of a class, the Java Virtual Machine must immediately check to see if any loading constraints are violated. If so, the record is retracted, the Java Virtual Machine throws a LinkageError, and the loading operation that caused the recording to take place fails.
Similarly, after imposing a loading constraint (see §5.4.2, §5.4.3.2, §5.4.3.3, and §5.4.3.4), the Java Virtual Machine must immediately check to see if any loading constraints are violated. If so, the newly imposed loading constraint is retracted, the Java Virtual Machine throws a LinkageError, and the operation that caused the constraint to be imposed (either resolution or preparation, as the case may be) fails.
The situations described here are the only times at which the Java Virtual Machine checks whether any loading constraints have been violated. A loading constraint is violated if, and only if, all the following four conditions hold:
- There exists a loader
Lsuch thatLhas been recorded by the Java Virtual Machine as an initiating loader of a class C namedN. - There exists a loader
L' such thatL' has been recorded by the Java Virtual Machine as an initiating loader of a class C ' namedN. - The equivalence relation defined by the (transitive closure of the) set of imposed constraints implies
N^L=N^{L'}. - C ≠ C '.
A full discussion of class loaders and type safety is beyond the scope of this specification. For a more comprehensive discussion, readers are referred to Dynamic Class Loading in the Java Virtual Machine by Sheng Liang and Gilad Bracha (Proceedings of the 1998 ACM SIGPLAN Conference on Object-Oriented Programming Systems, Languages and Applications).
5.3.5. Deriving a Class from a class File Representation
The following steps are used to derive a Class object for the nonarray class or interface C denoted by N using loader L from a purported representation in class file format.
-
First, the Java Virtual Machine determines whether it has already recorded that
Lis an initiating loader of a class or interface denoted byN. If so, this creation attempt is invalid and loading throws aLinkageError. -
Otherwise, the Java Virtual Machine attempts to parse the purported representation. However, the purported representation may not in fact be a valid representation of C.
This phase of loading must detect the following errors:
-
If the purported representation is not a
ClassFilestructure (§4.1, §4.8), loading throws an instance ofClassFormatError. -
Otherwise, if the purported representation is not of a supported major or minor version (§4.1), loading throws an instance of
UnsupportedClassVersionError.UnsupportedClassVersionError, a subclass ofClassFormatError, was introduced to enable easy identification of aClassFormatErrorcaused by an attempt to load a class whose representation uses an unsupported version of theclassfile format. In JDK release 1.1 and earlier, an instance ofNoClassDefFoundErrororClassFormatErrorwas thrown in case of an unsupported version, depending on whether the class was being loaded by the system class loader or a user-defined class loader. -
Otherwise, if the purported representation does not actually represent a class named
N, loading throws an instance ofNoClassDefFoundErroror an instance of one of its subclasses.
-
-
If C has a direct superclass, the symbolic reference from C to its direct superclass is resolved using the algorithm of §5.4.3.1. Note that if C is an interface it must have
Objectas its direct superclass, which must already have been loaded. OnlyObjecthas no direct superclass.Any exceptions that can be thrown due to class or interface resolution can be thrown as a result of this phase of loading. In addition, this phase of loading must detect the following errors:
- If the class or interface named as the direct superclass of C is in fact an interface, loading throws an
IncompatibleClassChangeError. - Otherwise, if any of the superclasses of C is C itself, loading throws a
ClassCircularityError.
- If the class or interface named as the direct superclass of C is in fact an interface, loading throws an
-
If C has any direct superinterfaces, the symbolic references from C to its direct superinterfaces are resolved using the algorithm of §5.4.3.1.
Any exceptions that can be thrown due to class or interface resolution can be thrown as a result of this phase of loading. In addition, this phase of loading must detect the following errors:
- If any of the classes or interfaces named as direct superinterfaces of C is not in fact an interface, loading throws an
IncompatibleClassChangeError. - Otherwise, if any of the superinterfaces of C is C itself, loading throws a
ClassCircularityError.
- If any of the classes or interfaces named as direct superinterfaces of C is not in fact an interface, loading throws an
-
The Java Virtual Machine marks C as having
Las its defining class loader and records thatLis an initiating loader of C (§5.3.4).