gpt4 book ai didi

java - 自定义类加载器问题

转载 作者:行者123 更新时间:2023-11-30 04:52:13 25 4
gpt4 key购买 nike

接下来的问题是:我从 here 获取了基类加载器代码。但我的类加载器在某种程度上是特定的,它必须能够从文件系统加载类(以 WinOS 为例),因此在类加载器中必须有一些 setAdditionalPath() 方法,该方法设置路径(a文件系统上的目录),我们将从中加载类(仅 *.class,无 jar)。这是代码,它从链接修改加载器(您可以看到,仅修改了 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 文件加载类。

Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be opened as needed.

它还支持父类加载器。如果这个类加载器不适合您的要求,也许您可​​以更详细地指定您需要的内容。无论如何,您可以查看源代码并基于它派生您自己的类加载器类。

下面是一个简短的工作代码片段,它演示了如何从 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" );

关于java - 自定义类加载器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9592021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com