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

1

9

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.

Egerton answered 26/3, 2011 at 18:13 Comment(0)
G
13

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
}
Guildhall answered 26/3, 2011 at 18:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.