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); } }
參考文章: