1

I'm trying to load classes from a jar file, some classes are loaded but then it throws a classNotFoundException on some of them (even if I catch the exception, it still throws it I really don't know how).

Here is the code (which I found here and works perfectly for everyone) :

    for (File jarFilePath : jarFilePaths) {
        pathToJar = jarFilePath.getAbsolutePath();
        jarFile = new JarFile(pathToJar);
        jarFiles.add(jarFile);

        Enumeration e = jarFile.entries();
        URL[] urls = { new URL("jar:file:" + pathToJar + "!/") };
        URLClassLoader cl = URLClassLoader.newInstance(urls);

        log.debug("Loading classes from jar : " + jarFile.getName());
        while (e.hasMoreElements()) {
            JarEntry je = (JarEntry) e.nextElement();
            if (je.isDirectory() || !je.getName().endsWith(".class")) {
                continue;
            }
            // -6 because of .class
            String className = je.getName().substring(0, je.getName().length() - 6);
            className = className.replace('/', '.');
            Class c;
            try {
                c = cl.loadClass(className);
                classes.add(c);
                log.debug("Loaded : " + className);
            } catch (ClassNotFoundException e1) {
                log.debug("Did not load : " + className + " - ClassNotFoundException");
                //e1.printStackTrace();
            }
        }
    }

This code let me load the classes from the jar, it works well, BUT it throws a ClassNotFoundException on some classes and it isn't catched (my debug doesn't appear and the stack track is printed even if I put it in comment)

Edit : I added a catch for NoClassDefFoundError and now it catches the exception. However, I still don't know why it doesn't load those classes. I checked them, they are full .class files with no $ sign.

Yanis26
  • 247
  • 2
  • 13
  • Not every .class-file is a Class you can load with the ClassLoader. Log the class-name you are about to load (before loading) and you'll probably see that class-names with a $-sign in it fail (see also [here](http://stackoverflow.com/a/1075224/3080094) about the $-sign). – vanOekel Sep 27 '14 at 01:00
  • Interesting, I learned something, thanks. However, I printed the name of the class that it is trying to load and it doesn't have $ sign. And what I don't understand, I can't catch the exception ! Edit : I added a catch for NoClassDefFoundError and now I can catch the exception. But I still don't understand why it doesn't load them all (they are full .class files with no $ sign). – Yanis26 Sep 28 '14 at 21:31

0 Answers0