加载本地jar到系统中

java javafx 文章 2022-03-04 22:43 564 0 全屏看文

AI助手支持GPT4.0

public static void addJarByLibs() {
	try {
		// 系统类库路径
		File libPath = new File("libs/");
		// 获取所有的.jar和.zip文件
		File[] jarFiles = libPath.listFiles(
				(dir, name) -> name.endsWith(".jar")
		);
		if (jarFiles != null) {
			for (File file : jarFiles) {
				if (!PluginManageService.isPluginEnabled(file.getName())) {
					continue;
				}
				addJarClass(file);
			}
		}
		PluginManager.getInstance().loadLocalPlugins();
	} catch (Exception e) {
		log.error("添加libs中jar包到系统中异常:", e);
	}
}

public static void addJarClass(File jarFile) {
	try {
		log.info("Reading lib file: " + jarFile.getName());
		Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
		method.setAccessible(true); // 设置方法的访问权限
		// 获取系统类加载器
		URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
		URL url = jarFile.toURI().toURL();
		method.invoke(classLoader, url);
	} catch (Exception e) {
		log.error("添加libs中jar包到系统中异常:", e);
	}
}

代码来自gitee开源项目 xJavaFxTool

-EOF-

AI助手支持GPT4.0