views:

127

answers:

2

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.

+1  A: 

Is there a way to try to load a class and if it does not work, then do something else?

Assuming you had a class file in C:\ called Foo.class

public static void main(String[] args) {

    File f = new File("c:\\");
    if (f.exists()) {
        URLClassLoader CLoader;
        try {
            CLoader = new URLClassLoader(new URL[]{f.toURL()});
            Class loadedClass = CLoader.loadClass("Foo");
        } catch (ClassNotFoundException ex) {
        } catch (MalformedURLException ex) {
        }

    } else {
        //do something else...
    }

}
Amir Afghani
+6  A: 

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();
  }
}
Alex Miller
This seems to be exactly what I need, but I'll need to try it when I get into work tomorrow. Expect to be accepted sometime tomorrow morning. Thanks!
HalfBrian