Java有個比較傻的地方,沒有提供從程序目錄加載jar包的功能,包括class-path等的配置,所有基於【相對於當前工做目錄路徑】和【絕對路徑】兩種,並無【相對於程序路徑】。java
網上找了一些資料,東拼西湊把這個功能實現了。在須要的時候調用便可。url
package example.autoload; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; public class Utils { public static String getApplicationFolder() { String path = Utils.class.getProtectionDomain().getCodeSource().getLocation().getPath(); return new File(path).getParent(); } public static void loadJarsFromAppFolder(String sub_folder) throws Exception { String path = getApplicationFolder() + File.pathSeparator + sub_folder; File f = new File(path); if (f.isDirectory()) { for (File subf : f.listFiles()) { if (subf.isFile()) { loadJarFile(subf); } } } else { loadJarFile(f); } } public static void loadJarFile(File path) throws Exception { URL url = path.toURI().toURL(); URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(classLoader, url); } }
package example.autoload; public class test { public static void main(String[] args) { try { Utils.loadJarsFromAppFolder("lib"); } catch (Exception e) { e.printStackTrace(); } } }