package com.send.start;
import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class Start {
public static String libPath = "";
public static ClassLoader classLoader;
/**
* @param args
*/
public static void main(String[] args) {
libPath = args[0];
createClassLoader();
try {
Class clazz = classLoader.loadClass("cmbcagent.tianjin.gjj.dz.MapSender");
Method m = clazz.getDeclaredMethod("start", new Class[0]);
m.invoke(clazz.newInstance(), new Object[0]);
} catch (Exception e) {
throw new RuntimeException("");
}
}
public static void createClassLoader() {
File localFile1 = new File(libPath);
checkLibDir(localFile1);
ArrayList localArrayList = new ArrayList(64);
File localFile2 = new File(libPath);
getAllJarUrl(localArrayList, localFile2);
// File localFile3 = new File(this.libPath + "ext");
// getAllJarUrl(localArrayList, localFile3);
URL[] arrayOfURL = new URL[localArrayList.size()];
localArrayList.toArray(arrayOfURL);
System.out.println("******arrayOfURL.length: " + arrayOfURL.length);
for (int i = 0; i < arrayOfURL.length; ++i)
System.out.println(arrayOfURL[i]);
AppendableURLClassloader localAppendableURLClassloader = new AppendableURLClassloader(arrayOfURL, Thread.currentThread()
.getContextClassLoader());
classLoader = localAppendableURLClassloader;
Thread.currentThread().setContextClassLoader(classLoader);
}
public static void getAllJarUrl(List paramList, File paramFile) {
checkLibDir(paramFile);
String[] arrayOfString = listAllJarFile(paramFile);
File localFile = null;
int i = 0;
try {
i = 0;
while (true) {
if (i >= arrayOfString.length)
break;
localFile = new File(paramFile, arrayOfString[i]);
localFile = localFile.getCanonicalFile();
paramList.add(localFile.toURL());
++i;
}
} catch (Exception localException) {
localException.printStackTrace();
throw new RuntimeException("Bootstrap.listJar");
}
}
public static String[] listAllJarFile(File paramFile) {
return paramFile.list(new FilenameFilter() {
public boolean accept(File paramFile, String paramString) {
return (paramString.endsWith(".jar"));
}
});
}
public static void checkLibDir(File paramFile) {
if (!(paramFile.exists()))
throw new IllegalArgumentException("libPath.notExist");
if (!(paramFile.isDirectory()))
throw new IllegalArgumentException("libPath.notDirectory");
if (!(paramFile.canRead()))
throw new IllegalArgumentException("libPath.canNotRead");
}
}
注意事项:
1.启动的类要单独放在一个jar包中,即含有main方法的类
2.main方法中不能引用第三方jar文件中的类(即通过import来导入的类只能是jvm自动加载的基本类,不能是第三方的jar),如果要引用只能通过反射机制来加载
3.main方法中主要是通过使用URLClassLoader来加载第三方的jar文件,并设置到当前线程下,然后通过反射机制来加载具体类,然后运行工程
含有Main的类只是负责通过反射机制调用主程序,起到一个入口的作用,其他不做任何业务操作