问题描述
我想我理解类加载层次结构是如何工作的。 (JVM首先查看父层次结构)
I think I understand how class-loading hierarchies work. (the JVM looks into the parent hierarchy first)
所以我想创建一个ClassLoader,或者使用现有的库,这是一个完全独立的范围,并且不会看一下父ClassLoading层次结构。实际上我正在寻找启动一个单独的JVM的相同效果,但没有真正这样做。
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.
推荐答案
只需使用 URLClassLoader
并提供 null
作为父级。
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
}
这篇关于如何创建不会在父级中搜索加载类的ClassLoader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!