1 16 import java.io.File ; 17 18 import java.net.MalformedURLException ; 19 import java.net.URL ; 20 import java.net.URLClassLoader ; 21 22 import java.lang.reflect.InvocationTargetException ; 23 import java.lang.reflect.Method ; 24 25 import java.util.StringTokenizer ; 26 27 31 public class Loader { 32 33 static final boolean VERBOSE = true; 34 35 static final String REPOSITORIES = "loader.jar.repositories"; 36 static final String MAIN_CLASS = "loader.main.class"; 37 38 class RepositoryClassLoader extends URLClassLoader { 39 40 public RepositoryClassLoader(ClassLoader parent) { 41 super(new URL [0], parent); 42 } 43 44 public void addRepository(File repository) { 45 if (VERBOSE) System.out.println("Processing repository: " + repository); 46 47 if (repository.exists() && repository.isDirectory()) { 48 File [] jars = repository.listFiles(); 49 50 for (int i = 0; i < jars.length; i++) { 51 if (jars[i].getAbsolutePath().endsWith(".jar")) { 52 try { 53 URL url = jars[i].toURL(); 54 if (VERBOSE) System.out.println("Adding jar: " + jars[i]); 55 super.addURL(url); 56 } catch (MalformedURLException e) { 57 throw new IllegalArgumentException (e.toString()); 58 } 59 } 60 } 61 } 62 } 63 } 64 65 public static void main(String [] args) throws Exception { 66 new Loader ().run(args); 67 } 68 69 void run(String [] args) throws Exception 70 { 71 String repositories = System.getProperty(REPOSITORIES); 72 if (repositories == null) { 73 System.out.println("Loader requires the '" + REPOSITORIES + "' property to be set"); 74 System.exit(1); 75 } 76 77 String mainClass = System.getProperty(MAIN_CLASS); 78 if (mainClass == null) { 79 System.out.println("Loader requires the '" + MAIN_CLASS + "' property to be set"); 80 System.exit(1); 81 } 82 83 if (VERBOSE) System.out.println("-------------------- Loading --------------------"); 84 85 RepositoryClassLoader classLoader = new RepositoryClassLoader(this.getClass().getClassLoader()); 86 87 StringTokenizer st = new StringTokenizer (repositories, File.pathSeparator); 88 while (st.hasMoreTokens()) { 89 classLoader.addRepository(new File (st.nextToken())); 90 } 91 92 Thread.currentThread().setContextClassLoader(classLoader); 93 94 if (VERBOSE) System.out.println("-------------------- Executing -----------------"); 95 if (VERBOSE) System.out.println("Main Class: " + mainClass); 96 97 invokeMain(classLoader, mainClass, args); 98 } 99 100 void invokeMain(ClassLoader classloader, String classname, String [] args) 101 throws IllegalAccessException , InvocationTargetException , NoSuchMethodException , ClassNotFoundException 102 { 103 Class invokedClass = classloader.loadClass(classname); 104 105 Class [] methodParamTypes = new Class [1]; 106 methodParamTypes[0] = args.getClass(); 107 108 Method main = invokedClass.getDeclaredMethod("main", methodParamTypes); 109 110 Object [] methodParams = new Object [1]; 111 methodParams[0] = args; 112 113 main.invoke(null, methodParams); 114 } 115 }
| Popular Tags
|