温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

利用java怎么将外部jar包添加到lasspath

发布时间:2020-12-04 16:29:49 来源:亿速云 阅读:161 作者:Leah 栏目:编程语言

利用java怎么将外部jar包添加到lasspath?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

java动态添加外部jar包到classpath的实例详解

前言:

  在项目开发过程中我们有时候需要动态的添加外部jar包,但是具体的业务需求还没有遇到过,因为如果动态添加外部jar包后,我们就需要修改业务代码,而修改代码就需要重新启动服务,那样好像就没有必要动态添加外部jar包了,怎么样才能不重新启动服务器就可以使用最新的代码我没有找到方法,如果各位知道的话给我点建议,回归主题,实现动态添加外部jar包到classpath的方法如下:

String beanClassName = "com.dynamic.DynamicBean3"; 
Map<String,Class<&#63;>> classMap = new HashMap<String,Class<&#63;>>(); 
String filePath = "f:\\testDynamicBean-1.0-SNAPSHOT.jar"; 
String uFilePath = "file:f:\\testDynamicBean-1.0-SNAPSHOT.jar"; 
 
URL url1 = new URL(uFilePath); 
URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url1 }, Thread.currentThread() 
        .getContextClassLoader()); 
List<JarEntry> jarEntryList = new ArrayList<>(); 
JarFile jarFile = new JarFile(filePath); 
Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries(); 
while (jarEntryEnumeration.hasMoreElements()){ 
   JarEntry jarEntry = jarEntryEnumeration.nextElement(); 
   if (//jarEntry.getName().startsWith(filePath) && 
      jarEntry.getName().endsWith(".class")) { 
        jarEntryList.add(jarEntry); 
      } 
    } 
 
   for (JarEntry entry : jarEntryList) { 
      String className = entry.getName().replace('/', '.'); 
      className = className.substring(0, className.length() - 6); 
      if(!classMap.containsKey(beanClassName)){ 
        Class<&#63;> loadClass = urlClassLoader.loadClass(className); 
        classMap.put(className,loadClass); 
      } 
    } 
    try { 
      Method printMethod = classMap.get(beanClassName).getMethod("printBean3"); 
      printMethod.invoke(classMap.get(beanClassName).newInstance()); 
    } catch (IllegalAccessException e) { 
      e.printStackTrace(); 
    } catch (InvocationTargetException e) { 
      e.printStackTrace(); 
    } catch (NoSuchMethodException e) { 
      e.printStackTrace(); 
    } catch (InstantiationException e) { 
      e.printStackTrace(); 
    } 

关于利用java怎么将外部jar包添加到lasspath问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI