Load classes from a folder without specifying a package

I have an application that allows people to write their own implementations using an abstract class. I load these implementations as .class files from a directory. I currently have this solution:

File classDir = new File("/users/myproject/classes/");

URL[] url = { classDir.toURI().toURL() };
URLClassLoader urlLoader = new URLClassLoader(url);

String filename;
for (File file : classDir.listFiles()) {
    filename = string.getFilenameWithoutExtension(file);
    if (filename.equals(".") || filename.equals("..") || filename.startsWith("."))
        continue;

AbstractClass instance = (AbstractClass)urlLoader
    .loadClass("org.mypackage." + filename)
    .getConstructor(ConfigUtil.class, DatabaseUtil.class, StringUtil.class)
    .newInstance(config, database, string));

    instance.doSomething();
}

As you can see, I need to specify the package in which the classes are located in order to load them correctly. Omitting the package, I get

 java.lang.NoClassDefFoundError:
     MyClass (wrong name: org/mypackage/MyClass)

error.

Now, from the architectural POV, I think it is very poorly designed, that classes created by other people should be compiled into a MY package when they are loaded.

So, I ask you: is there a way to load classes from the file system without having to specify the package in which they are located?

+5
source share
2

; ( ).

( SO-, > ) . " Java" " Java" .

Java Plugin Framework . , , , .

+3
+1

All Articles