Search code examples
javaclassdynamicclassloader

Detect whether Java class is loadable


I have two programs: one CLI program, and one GUI. The GUI is a frontend for the CLI, but also a GUI for another program as well.

I am importing the CLI's classes and extending them in the GUI to add GUI elements to the classes, and all is great.

But now I want to split the CLI that I currently have embedded in the GUI (as an included JAR). The JAR is in a fixed location (/opt/program/prog.jar), and the application will only be used on Linux, so I realize that this breaks traditional Java thought.

I've edited the ClassPath in the Manifest file to reflect this change, and it works fine. However, when I remove the file, the GUI fails to load, citing not being able to load the class.

Is there a way to try to load a class and if it does not work, then do something else? In essence, I'm trying to catch the ClassNotFound exception, but have not had any luck yet.


Solution

  • One common way to check for class existence is to just do a Class.forName("my.Class"). You can wrap that with a try/catch that catches ClassNotFoundException and decide what to do. If you want, you could do that in a wrapper class that has a main(). You could try to load the class and if it succeeds, then call main() on the loaded class and if not, do something else.

    public static void main(String arg[]) {
      try { 
        Class.forName("my.OtherMain");
    
        // worked, call it
        OtherMain.main();
      } catch(ClassNotFoundException e) {
        // fallback to some other behavior
        doOtherThing();
      }
    }