【发布时间】:2012-10-20 11:12:04
【问题描述】:
我正在尝试将 JAR 文件添加到类路径并在运行时从 JAR 文件加载所有类。这是我为此任务编写的代码(此类扩展 URLClassLoader)
public void loadJar(final String fName) throws IOException, IllegalAccessException, ClassNotFoundException {
final File file = new File(fName);
if (file.exists() && getFileExtension(file.getName()).equalsIgnoreCase("jar")) {
addURL(file.toURI().toURL());
for(final URL url : getURLs()){
System.out.println(url.toString());
}
final ZipFile jarFile = new ZipFile(file, ZipFile.OPEN_READ);
final Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) jarFile.entries();
while (entries.hasMoreElements()) {
final String className = getClassCanonicalName(entries.nextElement());
if (className != null) {
loadClass(getClassCanonicalName(entries.nextElement()));
}
}
}
}
private String getFileExtension(final String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
private String getClassCanonicalName(final ZipEntry entry) {
final String entryName = entry.getName();
if (getFileExtension(entryName).toLowerCase().endsWith("class")) {
return entryName.replaceAll(File.separator, ".");
} else {
return null;
}
}
但我不断收到类实体的 ClassNotFoundException,即使通过 getURLs 确实表明 jar 文件已添加到此加载器。
这个问题的原因是什么?谢谢
【问题讨论】:
标签: java jar classloader classnotfoundexception urlclassloader