问题
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.
回答1:
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
}
来源:https://stackoverflow.com/questions/5444246/how-do-i-create-a-classloader-that-will-not-search-the-parent-for-loading-classe