javadynamic-class-loadersdynamic-class

Dynamic external class loading


I trying to get experience with dynamic class loading in Java. So any comments and help are welcome. I have a program that allow the user to select a file and do some actions on it. The actions are "Commands", those are the class I try to load.

The way it works is : the user put a .class file a the desired folder, my program checks the files in the folder and if there's a class in a .class file, it loads it.

I did it, but not as I wanted. For now, it works only with the classes that have been compiled with my program. But what I want is that I could put any .class file that contains a class in the folder and my program loads it. That's my code for now :

for (int i = 0; i < fileList.length; i++) {
    if (fileList[i].endsWith(".class")) {
        /////MY FIRT TRY/////ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
        ClassLoader classLoader = FileMod.class.getClassLoader();

        // Define a class to be loaded.
        String classNameToBeLoaded = fileList[i].replace(".class", "");

        // Load the class
        try {
            /////MY FIRST TRY/////Class myClass = myClassLoader.loadClass(classNameToBeLoaded);
            //if the class exists in the file
            Class aClass = classLoader.loadClass(classNameToBeLoaded);
            classList.add(aClass);
            System.out.println("CLASS FOUND : " + classNameToBeLoaded + aClass.getSuperclass());
        } catch (ClassNotFoundException e) {
            System.out.println("CLASS NOT FOUND : " + classNameToBeLoaded);
            continue;
        }
    }
}

As you can see, I have tried two ways, the first one is currently in comments. What I do is checking every file in the folder and check if it's a .class file, if yes I try to load the class if there is one. I guess that the two classLoaders can only load the files they "know", so how Could I load a external class.


Solution

  • You generally need a new class loader. Use java.net.URLClassLoader.newInstance. Careful though, you are now loading classes from outside into your application.

    (Some class loaders will allow you to add locations, but that's a real hack.)