1 4 package org.oddjob.launch; 5 6 import java.io.File ; 7 import java.lang.reflect.Method ; 8 import java.net.MalformedURLException ; 9 import java.net.URL ; 10 import java.net.URLClassLoader ; 11 12 25 public class Launcher { 26 27 public static final String MAIN_CLASS = "org.oddjob.Main"; 28 29 public static void main(String args[]) { 30 try { 31 Launcher launcher = new Launcher(); 32 launcher.run(args); 33 } catch (Throwable t) { 34 t.printStackTrace(); 35 } 36 } 37 38 void run(String args[]) { 39 ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); 40 ClassLoader loader = getClassLoader(currentLoader); 41 Thread.currentThread().setContextClassLoader(loader); 42 try { 43 Class mainClass = loader.loadClass(MAIN_CLASS); 44 45 Method method = mainClass 48 .getMethod("main", 49 new Class [] { new String [0].getClass() }); 50 method.invoke(null, new Object [] { args }); 51 } catch (Throwable t) { 52 t.printStackTrace(); 53 } finally { 54 Thread.currentThread().setContextClassLoader(currentLoader); 55 } 56 } 57 58 ClassLoader getClassLoader(ClassLoader currentLoader) { 59 File sourceJar = Locator.getClassSource(getClass()); 60 File jarDir = sourceJar.getParentFile(); 61 62 File [] libFiles = new FileSpec(new File (new File (jarDir,"lib"), "*.jar")).getFiles(); 63 File [] optFiles = new FileSpec(new File (new File (jarDir,"opt/lib"), "*.jar")).getFiles(); 64 65 URL [] urls = new URL [2 + libFiles.length + optFiles.length]; 66 try { 67 urls[0] = sourceJar.toURL(); 68 urls[1] = new File (jarDir, "opt/classes").toURL(); 69 int index = 2; 70 for (int i = 0; i < libFiles.length; ++i) { 71 urls[index++] = libFiles[i].toURL(); 72 } 73 for (int i = 0; i < optFiles.length; ++i) { 74 urls[index++] = optFiles[i].toURL(); 75 } 76 } 77 catch (MalformedURLException e) { 78 e.printStackTrace(); 79 } 80 81 ClassLoader cl = new URLClassLoader (urls); 82 return cl; 83 } 84 } 85 | Popular Tags |