zoukankan      html  css  js  c++  java
  • java动态加载jar文件

    public static void main(String[] args)
                throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException,
                SecurityException, ClassNotFoundException, InstantiationException, MalformedURLException {
    //         String path =
    //         "/xx/.m2/repository/org/apache/commons/commons-lang3/3.1/commons-lang3-3.1.jar";
            String path = "commons-lang3-3.1.jar";//jar文件需放在工程目录下
    
            loadJar(path);
            Class<?> aClass = Class.forName("org.apache.commons.lang3.StringUtils");
            Object instance = aClass.newInstance();
            Object strip = aClass.getDeclaredMethod("strip", String.class, String.class).invoke(instance,
                    "[1,2,3,4,5,6,2,3,5,1]", "[]");
            System.out.println(strip);
    
        }
    
        private static void loadJar(String jarPath) throws MalformedURLException {
            File jarFile = new File(jarPath); // 从URLClassLoader类中获取类所在文件夹的方法,jar也可以认为是一个文件夹
    
            if (jarFile.exists() == false) {
                System.out.println("jar file not found.");
                return;
            }
    
            //获取类加载器的addURL方法,准备动态调用
            Method method = null;
            try {
                method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            } catch (NoSuchMethodException | SecurityException e1) {
                e1.printStackTrace();
            } 
            
            // 获取方法的访问权限,保存原始值
            boolean accessible = method.isAccessible();
            try {
                //修改访问权限为可写
                if (accessible == false) {
                    method.setAccessible(true);
                }
    
                // 获取系统类加载器
                URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
                
                //获取jar文件的url路径
                java.net.URL url = jarFile.toURI().toURL();
                
                //jar路径加入到系统url路径里
                method.invoke(classLoader, url);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //回写访问权限
                method.setAccessible(accessible);
            }
    
        }

    参考文章:

    Java动态加载jar及class文件

  • 相关阅读:
    kettle入门(四) 之kettle取昨天时间&设置任意时间变量案例
    用法
    Win10任务计划调度执行kettle作业
    Kettle 合并记录和Merge Join组件实现数据增量迁移(数据同步比插入更新快)
    鼠标右键新建没有excel
    python的to_sql
    leetcode1105 Filling Bookcase Shelves
    leetcode96 Unique Binary Search Trees
    leetcode111 Minimum Depth of Binary Tree
    leetcode128 Longest Consecutive Sequence
  • 原文地址:https://www.cnblogs.com/jiftle/p/11078638.html
Copyright © 2011-2022 走看看