Search code examples
javaclassclassloader

Quick fix for Class.forName case issue


I get this really (stupid) error from Java

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: models/modelclass (wrong name: models/ModelClass)

So I am typing in a command at the command line, and I would rather not type the proper case of the class name. I'd like to type "modelclass" instead of "ModelClass".

Is there a way to solve this? Why does this exception exist?!?


Solution

  • The error exists because the standard Java classloaders are case-sensitive to class names.

    Three options:

    1. Ignore standard Java conventions and name all your classes lowercase (not recommended, and not possible if you are looking for a third-party class).
    2. Use Google's Reflections Library to look up classes in your classpath, do a case insensitive match against the given input, and use the class you find from reflection in your Class.forName() call.
    3. Iteration on #2: Write your own classloader that does a case-insensitive search for classes and loads the one you want.