栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

java如何在运行时动态加载JAR文件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java如何在运行时动态加载JAR文件?

很难的原因是安全性。类加载器是不可变的。您不应在运行时随意向其添加类。实际上,我很惊讶能与系统类加载器一起使用。这是制作自己的子类加载器的方法:

URLClassLoader child = new URLClassLoader(        new URL[] {myJar.toURI().toURL()},        this.getClass().getClassLoader());Class classToLoad = Class.forName("com.MyClass", true, child);Method method = classToLoad.getDeclaredMethod("myMethod");Object instance = classToLoad.newInstance();Object result = method.invoke(instance);

以下解决方案有些骇人,因为它使用反射来绕过封装,但是可以完美地工作:

File file = ...URL url = file.toURI().toURL();URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);method.setAccessible(true);method.invoke(classLoader, url);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/368472.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号