184

In a few simple sentences, what is a Java ClassLoader, when is it used and why?

OK, I read a wiki article. ClassLoader loads classes. OK. So if I include jar files and import, a ClassLoader does the job.

Why should I bother with this ClassLoader? I've never used it and didn't know it existed.

The question is, why does the ClassLoader class exist? And also, how do you use it in practice? (Cases exist, I know.)

3
  • You'll get better results if you narrow down your question, e.g. by pointing a specific part you don't understand, how it relates to some other language you're familiar with, etc.
    – JRL
    Mar 11, 2010 at 11:56
  • 77
    This is a completely reasonable question, when viewed from the perspective of someone searching for a few simple sentences to explain the concept Mar 11, 2010 at 12:10
  • 1
    This video might be of interest: Do You Really Get Class Loaders?
    – asmaier
    Oct 30, 2013 at 10:49

8 Answers 8

244
+100

Taken from this nice tutorial from Sun:

Motivation

Applications written in statically compiled programming languages, such as C and C++, are compiled into native, machine-specific instructions and saved as an executable file. The process of combining the code into an executable native code is called linking - the merging of separately compiled code with shared library code to create an executable application. This is different in dynamically compiled programming languages such as Java. In Java, the .class files generated by the Java compiler remain as-is until loaded into the Java Virtual Machine (JVM) -- in other words, the linking process is performed by the JVM at runtime. Classes are loaded into the JVM on an 'as needed' basis. And when a loaded class depends on another class, then that class is loaded as well.

When a Java application is launched, the first class to run (or the entry point into the application) is the one with public static void method called main(). This class usually has references to other classes, and all attempts to load the referenced classes are carried out by the class loader.

To get a feeling of this recursive class loading as well as the class loading idea in general, consider the following simple class:

public class HelloApp {
   public static void main(String argv[]) {
      System.out.println("Aloha! Hello and Bye");
   }
}

If you run this class specifying the -verbose:class command-line option, so that it prints what classes are being loaded, you will get an output that looks as follows. Note that this is just a partial output since the list is too long to show here.

prmpt>java -verbose:class HelloApp



[Opened C:\Program Files\Java\jre1.5.0\lib\rt.jar]
[Opened C:\Program Files\Java\jre1.5.0\lib\jsse.jar]
[Opened C:\Program Files\Java\jre1.5.0\lib\jce.jar]
[Opened C:\Program Files\Java\jre1.5.0\lib\charsets.jar]
[Loaded java.lang.Object from shared objects file]
[Loaded java.io.Serializable from shared objects file]
[Loaded java.lang.Comparable from shared objects file]
[Loaded java.lang.CharSequence from shared objects file]
[Loaded java.lang.String from shared objects file]
[Loaded java.lang.reflect.GenericDeclaration from shared objects file]
[Loaded java.lang.reflect.Type from shared objects file]
[Loaded java.lang.reflect.AnnotatedElement from shared objects file]
[Loaded java.lang.Class from shared objects file]
[Loaded java.lang.Cloneable from shared objects file]
[Loaded java.lang.ClassLoader from shared objects file]
[Loaded java.lang.System from shared objects file]
[Loaded java.lang.Throwable from shared objects file]
.
.
.
[Loaded java.security.BasicPermissionCollection from shared objects file]
[Loaded java.security.Principal from shared objects file]
[Loaded java.security.cert.Certificate from shared objects file]
[Loaded HelloApp from file:/C:/classes/]
Aloha! Hello and Bye
[Loaded java.lang.Shutdown from shared objects file]
[Loaded java.lang.Shutdown$Lock from shared objects file]

As you can see, the Java runtime classes required by the application class (HelloApp) are loaded first.

Class Loaders in the Java 2 Platform

The Java programming language keeps evolving to make the life of applications developers easier everyday. This is done by providing APIs that simplify your life by allowing you to concentrate on business logic rather than implementation details of fundamental mechanisms. This is evident by the recent change of J2SE 1.5 to J2SE 5.0 in order to reflect the maturity of the Java platform.

As of JDK 1.2, a bootstrap class loader that is built into the JVM is responsible for loading the classes of the Java runtime. This class loader only loads classes that are found in the boot classpath, and since these are trusted classes, the validation process is not performed as for untrusted classes. In addition to the bootstrap class loader, the JVM has an extension class loader responsible for loading classes from standard extension APIs, and a system class loader that loads classes from a general class path as well as your application classes.

Since there is more than one class loader, they are represented in a tree whose root is the bootstrap class loader. Each class loader has a reference to its parent class loader. When a class loader is asked to load a class, it consults its parent class loader before attempting to load the item itself. The parent in turn consults its parent, and so on. So it is only after all the ancestor class loaders cannot find the class that the current class loader gets involved. In other words, a delegation model is used.

The java.lang.ClassLoader Class

The java.lang.ClassLoader is an abstract class that can be subclassed by applications that need to extend the manner in which the JVM dynamically loads classes. Constructors in java.lang.ClassLoader (and its subclasses) allow you to specify a parent when you instantiate a new class loader. If you don't explicitly specify a parent, the virtual machine's system class loader will be assigned as the default parent. In other words, the ClassLoader class uses a delegation model to search for classes and resources. Therefore, each instance of ClassLoader has an associated parent class loader, so that when requested to find a class or resources, the task is delegated to its parent class loader before attempting to find the class or resource itself. The loadClass() method of the ClassLoader performs the following tasks, in order, when called to load a class:

If a class has already been loaded, it returns it. Otherwise, it delegates the search for the new class to the parent class loader. If the parent class loader doesn't find the class, loadClass() calls the method findClass() to find and load the class. The finalClass() method searches for the class in the current class loader if the class wasn't found by the parent class loader.


There's more in the original article, which also shows you how to implement your own network class loaders, which answers your question as to why (and how). See also the API docs.

0
49

Most Java developers will never need to explicitly use class loaders (except to load resources so that it still works when they're bundled in JARs), let alone write their own.

ClassLoaders are used in large systems and server applications to do things like:

  • Modularize a system and load, unload and update modules at runtime
  • Use different versions of an API library (e.g. an XML parser) in parallel
  • Isolate different applications running within the same JVM (ensuring they don't interfere with each other, e.g. through static variables)
32

The question is "Why should one bother this ClassLoader class exists" ?

Well, mostly so you can fix things if they go wrong :-).

It's true, as long as you just write an application, compile it to a JAR and maybe include a few extra library JARs, you don't need to know about class loaders, it will just work.

Still, it is helpful to know a bit about class loaders and class loading to better understand what goes on behind the scenes. As an example, "static initializers" will run when a class is loaded, so to understand when they will run, you need to know how the class loader decides when to load them.

also.. how do you use it in practice ?

For simple cases, you don't need them. However, if you need to load code dynamically at runtime with explicit control where it comes from (e.g. loading over a network, loading plugins not available at compile time, etc.), you may need to do more. Then you can e.g. write your own class loader. See the other answers for links.

19

ClassLoader in Java is a class which is used to load class files in Java. Java code is compiled into class file by javac compiler and JVM executes Java program, by executing byte codes written in class file.

ClassLoader is responsible for loading class files from file system, network or any other source. There are three default class loader used in Java, Bootstrap , Extension and System or Application class loader.

ClassLoader


How ClassLoader works

## ClassLoader interaction with JVM enter image description here

More @ : how-classloader-works-in-java.html

7

Class Loaders are a functional component of JVM, which loads class data from the '.class' file or from over the network in to the Method Area in Heap.

Looks like a integral part of the JVM, but as an end java user why should I be concerned? Here is why:

Each class loader has it's own name space and classes invoked by a particular class loader gets into it's name space.

Classes invoked by two different class loaders will not have visibility over each other, resulting in enhanced security.

Class loader parent child delegation mechanism ensures java api classes could never be hacked by unauthorized code.

For details look here

1

Class loaders are hierarchical. Classes are introduced to the JVM as they are referenced by name in a class that is already running in the JVM.

How the very first class loaded?
The very first class is loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running.

A class loader creates a namespace. All JVM include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. That is one thing, and we will look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Here are the class loaders created by the JVM.

Bootstrap (primordial) This class loader not re loadable. Loads JDK internal classes, java.* packages ( typically loads rt.jar and i18n.jar). Extesions This class loader not re loadable. Loads jar files from JDK extensions directory (usually lib/ext of JRE). System This class loader not re loadable. Loads classes from system class path.

http://www.sbalasani.com/2015/01/java-class-loaders.html

1

When you asking why does the ClassLoader class exist, the reason is pretty simple - it's the class responsible for finding and loading class files at run time.

Let's elaborate it.

In JVM, every Class is loaded by some instance of java.lang.ClassLoader. Whenever a new JVM is started by you usual Java program launching java <classname> command, the first step is to load all the key classes in memory required for proper working like java.lang.Object and other runtime classes (rt.jar).

Now, there are actually 3 parts to ClassLoader:

  • The BootstrapClassLoader is responsible for making these classes available i.e. loading these classes in memory.

  • The next task is to load any external libraries / JARs into the memory for proper working of the application. The ExtClassLoader is responsible for this task. This class loader is responsible for loading all the .jar files mentioned in java.ext.dirs path.

  • The third and the main important class loader is the AppClassLoader. The application class loader is responsible for loading of the class files mentioned in the java.class.path system property.

It's also important to note that the default ClassLoader implementations could be overridden enabling you to customize the JVM in useful and interesting ways, allowing you to completely redefine how class files are brought into the system.

enter image description here

Check it out to learn more about Java Class Loader.

0

ClassLoader

ClassLoader is a part of Java Runtime Environment(JRE) which dynamically loads classes(envirompment objects - java.lang.Class and files .class) into JVM(Java Virtual Machine). JRE uses lazy class loading(on demand) it can reduce memory footprint. When application required some class JRE asks ClassLoader to load this class

There is an hierarchy of ClassLoader class

  • BootStrap or Primodial - root and is built-in(returns null when getClassLoader()) JDK classes. Loads classes from rt.jar
  • Extension(Platform Java v9) - core java classes. Loads classes from jre/lib/ext directory or pointed by java.ext.dirs system property
  • System/Application - application classes from classpath[About] or command line option(-cp, -classpath)

Also you are able to create your own ClassLoader class for your specific case. For example loading class from some repository, working with versionning, unloading, security

To check who exactly loads your class use getClassLoader()

SomeClass.class.getClassLoader()

Finding class flow(delegation model)

child classloader find in cache 
    if not 
        parent classloader find in cache 
            if not
        parent classloader try to load
    if not
child classloader try to load

[ClassNotFoundException vs NoClassDefFoundError and Implicit vs Explicit class loading]

[iOS Dynamic Linker]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.