接下来的问题是:我从以下位置获取了基类加载器代码here。但我的类加载器在某种程度上是特定的,它必须能够从文件系统加载类(让我们以WinOS为例),所以在类加载器中必须有一些setAdditionalPath()
方法,它设置一个路径(文件系统上的目录),我们将从中加载类(仅 *.class,没有 jars)。这是代码,它从链接修改加载器(您可以看到,仅修改了 loadClass),但它无法正常工作:
public void setAdditionalPath(String dir) {
if(dir == null) {
throw new NullPointerException("");
}
this.Path = dir;
}
public Loader(){
super(Loader.class.getClassLoader());
}
public Class loadClass(String className) throws ClassNotFoundException {
if(Path.length() != 0) {
File file = new File(Path);
try {
// Convert File to an URL
URL url = file.toURL();
URL[] urls = new URL[]{url};
// Create a new class loader with the directory
ClassLoader cl = new URLClassLoader(urls);
ClassLoader c = cl.getSystemClassLoader();
Class cls = c.loadClass(className);
return cls;
} catch (MalformedURLException e) {
} catch (ClassNotFoundException e) {
}
}
return findClass(Path);
}
如果有人提供帮助,我将不胜感激:)
您可以只使用提供的框架java.net.URLClassLoader。无需自己编写。它支持从目录和 JAR 文件加载类。
任何以“/”结尾的 URL 都被假定为引用目录。
否则,URL 被假定为引用一个 JAR 文件,该文件将被
根据需要打开。
它还支持父类加载器。如果这个类加载器不适合您的要求,也许您可以更详细地指定您需要的内容。无论如何,您可以查看源代码并基于它派生您自己的类加载器类。
下面是一个简短的工作代码片段,它演示了如何从 URLClassLoader 按名称加载类:
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
// This URL for a directory will be searched *recursively*
URL classes =
new URL( "file:///D:/code/myCustomClassesAreUnderThisFolder/" );
ClassLoader custom =
new URLClassLoader( new URL[] { classes }, systemClassLoader );
// this class should be loaded from your directory
Class< ? > clazz = custom.loadClass( "my.custom.class.Name" );
// this class will be loaded as well, because you specified the system
// class loader as the parent
Class< ? > clazzString = custom.loadClass( "java.lang.String" );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)