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.

Exploring
  • 2,493
  • 11
  • 56
  • 97
Eran Medan
  • 44,555
  • 61
  • 184
  • 276

1 Answers1

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
}
Brian Roach
  • 76,169
  • 12
  • 136
  • 161