Instantiating and using a classloader
suggest changeThis 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.loadClass("com.example.MyObject");
URLClassLoader(URL[]) uses the system class loader as its parent. loadClass returns a class this loader has already defined. Otherwise it asks the parent, and only then looks in extras.jar. findClass is protected and searches only this loader’s URLs, so it does not do that parent-first lookup.
loadClass can fail in a variety of ways. The most common are:
- If the named class cannot be found, the call will throw
ClassNotFoundException. - If the named class depends on some other class that cannot be found, the call will throw
NoClassDefFoundError.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents