经常碰到需要动态加载jar及class文件的场景。Java类由于需要加载和编译字节码,动态加载class文件较为麻烦,但JDK仍提供了一整套方法来动态加载jar文件和class文件。

一、动态加载jar

// 系统类库路径
File libPath = new File(jar文件所在路径); // 获取所有的.jar和.zip文件
File[] jarFiles = libPath.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".jar") || name.endsWith(".zip");
}
}); if (jarFiles != null) {
// 从URLClassLoader类中获取类所在文件夹的方法
// 对于jar文件,可以理解为一个存放class文件的文件夹
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
boolean accessible = method.isAccessible(); // 获取方法的访问权限
try {
if (accessible == false) {
method.setAccessible(true); // 设置方法的访问权限
}
// 获取系统类加载器
URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
for (File file : jarFiles) {
URL url = file.toURI().toURL();
try {
method.invoke(classLoader, url);
LOG.debug("读取jar文件[name={}]", file.getName());
} catch (Exception e) {
LOG.error("读取jar文件[name={}]失败", file.getName());
}
}
} finally {
method.setAccessible(accessible);
}
}

二、动态加载class文件

// 设置class文件所在根路径
// 例如/usr/java/classes下有一个test.App类,则/usr/java/classes即这个类的根路径,而.class文件的实际位置是/usr/java/classes/test/App.class
File clazzPath = new File(class文件所在根路径); // 记录加载.class文件的数量
int clazzCount = 0; if (clazzPath.exists() && clazzPath.isDirectory()) {
// 获取路径长度
int clazzPathLen = clazzPath.getAbsolutePath().length() + 1; Stack<File> stack = new Stack<>();
stack.push(clazzPath); // 遍历类路径
while (stack.isEmpty() == false) {
File path = stack.pop();
File[] classFiles = path.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory() || pathname.getName().endsWith(".class");
}
});
for (File subFile : classFiles) {
if (subFile.isDirectory()) {
stack.push(subFile);
} else {
if (clazzCount++ == 0) {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
boolean accessible = method.isAccessible();
try {
if (accessible == false) {
method.setAccessible(true);
}
// 设置类加载器
URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
// 将当前类路径加入到类加载器中
method.invoke(classLoader, clazzPath.toURI().toURL());
} finally {
method.setAccessible(accessible);
}
}
// 文件名称
String className = subFile.getAbsolutePath();
className = className.substring(clazzPathLen, className.length() - 6);
className = className.replace(File.separatorChar, '.');
// 加载Class类
Class.forName(className);
LOG.debug("读取应用程序类文件[class={}]", className);
}
}
}
}

完成上述两步操作后,即可使用Class.forName来加载jar中或.class文件包含的Java类了。

Java动态加载jar及class文件的更多相关文章

  1. java动态加载jar文件

    public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, Invo ...

  2. java动态加载jar包,并运行其中的类和方法

    动态加载jar包,在实际开发中经常会需要用到,尤其涉及平台和业务的关系的时候,业务逻辑部分可以独立出去交给业务方管理,业务方只需要提供jar包,就能在平台上运行. 下面通过一个实例来直观演示: 第一: ...

  3. JAVA动态加载JAR包的实现

    如何动态的加载这些驱动!不可能把所有的数据库驱动都集成到JAR包中吧?!于是动态加载驱动的JAR包就产生了!其实这些在做系统基础代码时,经常用到,只是一般我们没有机会去搞而已. 动态加载JAR包,使用 ...

  4. JAVA动态加载JAR

    // 生成JAR包D:\TestClass.jar package hand.java.loadjar; public class TestClass { private String sayHell ...

  5. Java动态加载JAR包

    参考代码: package org; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import ...

  6. JAVA动态加载JAR包执行程序

    入口代码 import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.ne ...

  7. [转载] Java中动态加载jar文件和class文件

    转载自http://blog.csdn.net/mousebaby808/article/details/31788325 概述 诸如tomcat这样的服务器,在启动的时候会加载应用程序中lib目录下 ...

  8. Java_Java中动态加载jar文件和class文件

    转自:http://blog.csdn.net/mousebaby808/article/details/31788325 概述 诸如tomcat这样的服务器,在启动的时候会加载应用程序中lib目录下 ...

  9. Android动态加载jar/dex

    前言 在目前的软硬件环境下,Native App与Web App在用户体验上有着明显的优势,但在实际项目中有些会因为业务的频繁变更而频繁的升级客户端,造成较差的用户体验,而这也恰恰是Web App的优 ...

随机推荐

  1. Web Service学习之五:WSDL详解

    WSDL是Web Service定义文档,不同平台 不同语言实现Web Service遵循的共同协议 ,在解析XML时按照各自语言的特点解析成相应的具体类.方法.参数和数据类型. WSDL是一个XML ...

  2. Android实例-屏幕操持常亮(XE8+小米2)

    相关资料: http://www.bubuko.com/infodetail-163304.html 结果: 1.打开权限Wake lock为True. 第三方单元: unit Android.JNI ...

  3. Spring Auto scanning components

    Normally you declare all the beans or components in XML bean configuration file, so that Spring cont ...

  4. POJ 2528 Mayor's posters (线段树区间更新+离散化)

    题目链接:http://poj.org/problem?id=2528 给你n块木板,每块木板有起始和终点,按顺序放置,问最终能看到几块木板. 很明显的线段树区间更新问题,每次放置木板就更新区间里的值 ...

  5. jquery页面加载的时候加载函数

    http://blog.csdn.net/tjcyjd/article/details/6713474 jQuery 页面加载初始化的方法有3种 ,页面在加载的时候都会执行脚本,应该没什么区别,主要看 ...

  6. jq简单选项卡

    function tabControl(obj,elm){ $(obj).hover(function(){ $(this).addClass('active').siblings().removeC ...

  7. ios开源项目(各种有用的第三方库)

    状态栏:MTStatusBarOverlay  下拉刷新:EGOTableViewPullRefresh  网络应用:ASIHTTPRequest  等待特效:MBProgressHUD  JSON解 ...

  8. Boost的Serialization和SmartPoint搭配使用

    准确来说,这篇博文并不是译文,而是一篇某个网页中代码改写而来.原文章中的代码存在几处严重错误,网页又不提供留言功能(不是没有而是一个没有留言功能的留言板).4年过去了,作者对这些错误不更正让人无法接受 ...

  9. 简单的玩玩etimer <contiki学习笔记之九>

    好吧,我承认etimer有点小复杂,主要是它似乎和contiki的process搅在一起,到处都在call_process.那就先搜搜contiki下的etimer的example看看,然后再试着写一 ...

  10. update更新两个字段

    update更新两个字段时的sql语句: update tj_record set is_recycle_reprint_guide='1' , recycle__guide_date=now() w ...