I am trying to add JAR file to class path and load all classes from JAR file at run time. here is the code I wrote for this task (This class extends 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;
}
}
But I keep getting ClassNotFoundException for class entities even through getURLs does indicate jar files has been added to this loader.
What is the cause of this problem? Thanks
On Windows this will fail. It should be
/for the separator of aZipEntryfor a Zip made on any platform.So replace that with:
Also strip the class name. SSCCE E.G.:
Output