I think I understand how class-loading hierarchies work. (the JVM looks into the parent hierarchy first)
So I would like to create a ClassLoader, or use an existing library, that is a completely separate scope, and doesn't look at the parent ClassLoading hierarchy. Actually I'm looking for the same effect of launching a separate JVM, but without literally doing so.
I'm confident this is possible, but surprised it was so hard to find a simple example of how to do that.
As we can see, there are three different class loaders here: application, extension, and bootstrap (displayed as null). The application class loader loads the class where the example method is contained. An application or system class loader loads our own files in the classpath.
We will create our own ClassLoader by extending the ClassLoader class and overriding the loadClass(String name) method. If the class name will start from com. journaldev then we will load it using our custom class loader or else we will invoke the parent ClassLoader loadClass() method to load the class.
Custom class loaders You might want to write your own class loader so that you can load classes from an alternate repository, partition user code, or unload classes.
The parent-delegation modelIf a class loader's parent can load a given class, it returns that class. Otherwise, the class loader attempts to load the class itself. The JVM has three class loaders, each possessing a different scope from which it can load classes.
Simply use the URLClassLoader
and supply null
as the parent.
File myDir = new File("/some/directory/");
ClassLoader loader = null;
try {
URL url = myDir.toURL();
URL[] urls = new URL[]{url};
loader = new URLClassLoader(urls, null);
}
catch (MalformedURLException e)
{
// oops
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With