Java 熱載入jar包

u011270461發表於2013-08-30

1.最近想在專案裡面用上動態載入jar包的功能,就試著寫了小用例

package com.weizhi.hotdeploy;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @ClassName DeployJar
 * @Description 熱載入Jar包
 * @Author weizhi2018
 * @Date 2013-8-30 上午08:59:27
 * 
 */

public class DeployJar {
	// 字尾
	private final static String CLAZZ_SUFFIX = ".class";

	// 類載入器
	private ClassLoader classLoader;

	/**
	 * @Title loadPath
	 * @Description 建立載入器
	 * @Author weizhi2018
	 * @param jarPath
	 *            jar包所在路經
	 * @throws
	 */
	public void loadPath(String jarPath) {
		try {
			File jarFiles = new File(jarPath);

			File[] jarFilesArr = jarFiles.listFiles();
			URL[] jarFilePathArr = new URL[jarFilesArr.length];
			int i = 0;
			for (File jarfile : jarFilesArr) {
				String jarname = jarfile.getName();
				if (jarname.indexOf(".jar") < 0) {
					continue;
				}
				String jarFilePath = "file:\\" + jarPath + File.separator
						+ jarname;
				jarFilePathArr[i] = new URL(jarFilePath);
				i++;
			}

			classLoader = new URLClassLoader(jarFilePathArr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Title loadJar
	 * @Description 遍歷jar包下的類
	 * @Author weizhi2018
	 * @param jarName
	 *            jar包名字 完整路徑
	 * @throws
	 */
	public void loadJar(String jarName) {
		if (jarName.indexOf(".jar") < 0) {
			return;
		}
		try {
			JarFile jarFile = new JarFile(jarName);
			Enumeration<JarEntry> em = jarFile.entries();
			while (em.hasMoreElements()) {
				JarEntry jarEntry = em.nextElement();
				String clazzFile = jarEntry.getName();

				if (!clazzFile.endsWith(CLAZZ_SUFFIX)) {
					continue;
				}
				String clazzName = clazzFile.substring(0,
						clazzFile.length() - CLAZZ_SUFFIX.length()).replace(
						'/', '.');
				System.out.println(clazzName);

				// loadClass(clazzName);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Title loadClass
	 * @Description 通過類載入器例項化
	 * @Author weizhi2018
	 * @param clazzName
	 *            類名字
	 * @return
	 * @throws
	 */
	public Object loadClass(String clazzName) {
		if (this.classLoader == null) {
			return null;
		}
		Class clazz = null;
		try {
			clazz = this.classLoader.loadClass(clazzName);
			Object obj = clazz.newInstance();
			return obj;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoClassDefFoundError e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}
}

2.測試

package com.weizhi.hotdeploy;

import java.io.File;

/**
 * @ClassName DeployMain
 * @Description TODO
 * @Author weizhi2018 
 * @Date 2013-8-30 上午09:59:46 
 *
 */

public class DeployMain {

	public static void main(String[] args) {
		String libpath = System.getProperty("user.dir") +File.separator+ "lib";
	
		DeployJar deployJar = new DeployJar();
		
		deployJar.loadPath(libpath);
		
		System.out.println(deployJar.loadClass("org.dom4j.DocumentHelper"));
		
		String jarPath = libpath + File.separator + "commons-lang.jar";
		deployJar.loadJar(jarPath);
	}

}

3.lib 下面放一些jar包用來讀取

4.在建立載入器時報瞭如下錯誤

java.net.MalformedURLException: unknown protocol: d
	at java.net.URL.<init>(URL.java:574)
	at java.net.URL.<init>(URL.java:464)
	at java.net.URL.<init>(URL.java:413)
	at com.weizhi.hotdeploy.DeployJar.loadPath(DeployJar.java:52)
	at com.weizhi.hotdeploy.DeployMain.main(DeployMain.java:39)

原因就是:

      //要加上 "file:\\" 否則會報錯
      String jarFilePath = "file:\\" + jarPath + File.separator + jarname;


相關文章