Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a ClassLoader that will not search the parent for loading classes

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.

like image 689
Eran Medan Avatar asked Mar 26 '11 18:03

Eran Medan


People also ask

What are different types of ClassLoader?

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.

Can you create a custom class loader?

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.

When would you use a custom ClassLoader?

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.

What is parent ClassLoader?

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.


1 Answers

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
}
like image 119
Brian Roach Avatar answered Sep 23 '22 03:09

Brian Roach