1

Here's a really good example of NoClassDefFoundError

public class NoClassDefFoundErrorDemo {
    public static void main(String[] args) {
        try {
            // The following line would throw ExceptionInInitializerError
            SimpleCalculator calculator1 = new SimpleCalculator();
        } catch (Throwable t) {
            System.out.println(t);
        }
        // The following line would cause NoClassDefFoundError
        SimpleCalculator calculator2 = new SimpleCalculator();
    }
}

When the code throws, then the initialization in the bottom will not succeed and will throw NoClassDefFoundError, which makes sense.

Here's the question (actually a problem)

I have a Servlet-based Jar classloader that loads Jar from file system at runtime and is experiencing this similar error, the question would be, is there a way to get around the error without restarting the whole server? Or even renaming the package for the classes in the Jar?

quarks
  • 33,478
  • 73
  • 290
  • 513
  • 2
    I am not sure I understand what exactly is the specific issue? The class is loaded _sometime in the future?_ And you need to be able to call it properly the second time? – Matt Clark Nov 26 '18 at 23:14
  • What is the reason to go against basic fundamental Java conception? Of course there is a way to go around it, but you will never get your SimpleCalculator objects as long as there is no class for them available for JVM. – Vadim Nov 26 '18 at 23:18
  • @MattClark yes the example code is just to illustrate the concept, my system is quite more complex, it loads Jar from File System depending on the request from client apps, thus a JarClassLoader is in place. The problem is sometime Jar contains errors and when it is first loaded with an error then it will not load anymore even if the Jar is updated with fixes. – quarks Nov 26 '18 at 23:22
  • @xybrek If I understand correctly, this is actually an artifact of the default classloader. If you [read this](https://stackoverflow.com/a/6644467/1790644), or any other posts on the same topic, you will see that classes are used in the order they appear on the classpath. If you load the same class twice, only the earliest loaded version will be used. – Matt Clark Nov 26 '18 at 23:27
  • Actually even renaming the class and packaging with Maven shade plugin does not fix the NoClassDefFoundError (I just tested now) – quarks Nov 26 '18 at 23:30
  • The (name) of the jar does not matter. It would literally need to be a new (package | class) name if it is loaded onto the classpath a second time, otherwise resolution will always fall to the first instance of the class found, being the _old_ one. – Matt Clark Nov 26 '18 at 23:31

0 Answers0