// 2009-04-20 Christian d'Heureuse (chdh@inventec.ch): Module created. import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.util.List; import javax.swing.JOptionPane; public class JavaApplLauncher { public List classPath; // path names are relative to the directory of the JAR file of this class public String mainClassName; public boolean setCurrentDir = true; // true = set current directory to JAR directory private File baseDir; private ClassLoader newClassLoader; public boolean startAndDisplayError (String... args) { try { start (args); } catch (Throwable t) { t.printStackTrace(); showErrorMessage ("Error: "+t.toString(), "Error while launching application"); return false; } return true; } private static void showErrorMessage (String msg, String title) { JOptionPane.showMessageDialog (null, msg, title, JOptionPane.ERROR_MESSAGE); } public void start (String... args) throws Exception { baseDir = getBaseDir(); if (setCurrentDir) System.setProperty ("user.dir", baseDir.getAbsolutePath()); setClassLoader(); callMainClass (args); } private void setClassLoader() throws Exception { Thread thread = Thread.currentThread(); ClassLoader parentClassLoader = thread.getContextClassLoader(); if (parentClassLoader == null) parentClassLoader = JavaApplLauncher.class.getClassLoader(); if (parentClassLoader == null) parentClassLoader = ClassLoader.getSystemClassLoader(); URL[] cp = buildAbsoluteClassPath(); newClassLoader = new URLClassLoader(cp, parentClassLoader); thread.setContextClassLoader (newClassLoader); } private URL[] buildAbsoluteClassPath() throws Exception { URL[] cp = new URL[classPath.size()]; for (int i=0; i mainClass = Class.forName(mainClassName, true, newClassLoader); Method mainMethod = mainClass.getMethod("main", args.getClass()); mainMethod.invoke (null, (Object)args); } private File getBaseDir() throws Exception { URI uri = getClass().getProtectionDomain().getCodeSource().getLocation().toURI(); if (!"file".equals(uri.getScheme())) throw new Exception ("Unexpected scheme in JAR file URI: "+uri); File f = new File(uri.getSchemeSpecificPart()).getAbsoluteFile(); if (f.getName().endsWith(".jar")) f = f.getParentFile(); return f; } } // end class JavaApplLauncher