packageorg.apache.loadjar;importjava.io.BufferedReader;/*****/
importjava.io.File;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.lang.reflect.Method;importjava.net.URL;importjava.net.URLClassLoader;importjava.util.ArrayList;importjava.util.List;public final classExtClassPathLoader {private static Method addURL =initAddMethod();public static URLClassLoader classloader =(URLClassLoader) ClassLoader.getSystemClassLoader();/*** 初始化addUrl 方法.
*
*@return可访问addUrl方法的Method对象*/
private staticMethod initAddMethod() {try{//反射获取addURL方法
Method add = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class});//设置访问权限
add.setAccessible(true);returnadd;
}catch(Exception e) {throw newRuntimeException(e);
}
}/*** 加载jar classpath。*/
public static voidloadClasspath() {
List files =getJarFiles();if (files == null)return;for(String f : files) {
loadClasspath(f);
}
List resFiles =getResFiles();if (resFiles == null)return;for(String r : resFiles) {
loadResourceDir(r);
}
}private static voidloadClasspath(String filepath) {
File file= newFile(filepath);
loopFiles(file);
}private static voidloadResourceDir(String filepath) {
File file= newFile(filepath);
loopDirs(file);
}/** */
/*** 循环遍历目录,找出所有的资源路径。
*
*@paramfile
* 当前遍历文件*/
private static voidloopDirs(File file) {//资源文件只加载路径
if(file.isDirectory()) {
addURL(file);
File[] tmps=file.listFiles();for(File tmp : tmps) {
loopDirs(tmp);
}
}
}/*** 循环遍历目录,找出所有的jar包。
*
*@paramfile
* 当前遍历文件*/
private static voidloopFiles(File file) {if(file.isDirectory()) {
File[] tmps=file.listFiles();for(File tmp : tmps) {
loopFiles(tmp);
}
}else{if (file.getAbsolutePath().endsWith(".jar") || file.getAbsolutePath().endsWith(".zip")) {
addURL(file);
}
}
}/*** 通过filepath加载文件到classpath。
*
*@paramfilePath
* 文件路径
*@returnURL
*@throwsException
* 异常*/
private static voidaddURL(File file) {try{
addURL.invoke(classloader,newObject[] { file.toURI().toURL() });
}catch(Exception e) {
}
}/***
* 将当前classpath下jar.txt的清单jar明见加载到classpath中
*
*@return*@throwsException*/
private static ListgetJarFiles() {//TODO 从properties文件中读取配置信息 如果不想配置 可以自己new 一个List 然后把 jar的路径加进去//然后返回
InputStream in = ClassLoader.getSystemResourceAsStream("jar.txt");
BufferedReader br= new BufferedReader(newInputStreamReader(in));
String line= null;
List list = new ArrayList();try{
line=br.readLine();while (line != null) {
list.add(line);
line=br.readLine();
}
}catch(IOException e) {
e.printStackTrace();
}finally{try{if (br != null)
br.close();
}catch(IOException e) {
e.printStackTrace();
}
}returnlist;
}/*** 从配置文件中得到配置的需要加载classpath里的资源路径集合
*
*@return
*/
private static ListgetResFiles() {//TODO 从properties文件中读取配置信息略 如果不想配置 可以自己new 一个List 然后把//jar的路径加进去 然后返回 额 如果没有资源路径为空就可以了
return null;
}
}