0

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
castors33
  • 477
  • 10
  • 26

1 Answers1

3

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.)

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • that's exactly what I want loading classes which are outside, thanks I'll try it – castors33 Jan 25 '13 at 17:09
  • could i use a ClassLoader or it is prefered to use URLClassLoader? Why briefly. – castors33 Jan 25 '13 at 17:23
  • @castors33 Using `URLClassLoader.newInstance` adds in various extra features and checks, and should be easy enough to use. Also works in untrusted code. The class hierarchy for `ClassLoader` is a bit of a mess. – Tom Hawtin - tackline Jan 25 '13 at 17:31