7

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.

Exploring
  • 3,269
  • 8
  • 42
  • 69
Eran Medan
  • 43,837
  • 59
  • 177
  • 273

1 Answers1

11

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
}
Brian Roach
  • 74,513
  • 12
  • 132
  • 160