Java Language Instantiating and using a classloader


Example

This basic example shows how an application can instantiate a classloader and use it to dynamically load a class.

URL[] urls = new URL[] {new URL("file:/home/me/extras.jar")};
Classloader loader = new URLClassLoader(urls);
Class<?> myObjectClass = loader.findClass("com.example.MyObject");

The classloader created in this example will have the default classloader as its parent, and will first try to find any class in the parent classloader before looking in "extra.jar". If the requested class has already been loaded, the findClass call will return the reference to the previously loaded class.

The findClass call can fail in a variety of ways. The most common are:

  • If the named class cannot be found, the call with throw ClassNotFoundException.
  • If the named class depends on some other class that cannot be found, the call will throw NoClassDefFoundError.