URLClassLoader can't find classes
-
01-07-2021 - |
Question
I want to use an URLClassLoader to load classes in a particular directory from a jar-archive.
The project structure is as follows
/
application.jar
/lib/
mysql.jar
log4j.jar
...
/myClasses/
class1.class
class2.class
...
The jar has the following manifest:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_07-b10 (Oracle Corporation)
Main-Class: de.application.start
Class-Path: lib/mysql.jar lib/log4j.jar lib/....jar
What I do currently is iterating over all files within /myClasses/
and trying to load that particular class (they all have the same package) like this:
File classDir = new File("/path/to/my/root/folder/myClasses/");
URL[] url = { classdir.toURI().toURL() };
ClassLoader loader = new URLClassLoader(url);
for (File file : classDir.listFiles()) {
String filename = StringUtil.getFilenameWithoutExtension(file.getName());
loader.loadClass("de.myClasses." + filename).getConstructor().newInstance();
But, even though the files obviously exist, I always get a java.lang.ClassNotFoundException: de.myClasses.class1
error. What am I doing wrong?
Solution
You should put your compiled classes in directories according its packages.
So class de.myClasses.Class1
should be in directory /myClasses/de/myClasses/
.
OTHER TIPS
file.getName()
returns "Class1.class"
instead of "Class1"
, right? remove last 6 chars.
Also, if Class1 is in package de.myClasses
it should be at
<your_base_dir>/de/myClasses
and if Class1 is in top package (no package) then you should ask for it as
loader.loadClass("Class1") // no de.mClasses. prefix