package com.manulife.test;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
/**
* Created by hp on 2019/11/20.
*/
public class LoadJars {
public static void main(String[] args) throws Exception {
String path = "D:\\repository\\org\\apache\\commons\\commons-lang3\\3.1\\commons-lang3-3.1jar";
loadJar(path);
Class<?> aClass = Class.forName("org.apache.commons.lang3.StringUtils");
Object instance = aClass.newInstance();
Object ss = aClass.getDeclaredMethod("isBlank", CharSequence.class).invoke(instance, "");
System.out.println(ss);
}
public static void loadJar(String jarPath) {
File jarFile = new File(jarPath);
// 從URLClassLoader類中獲取類所在文件夾的方法,jar也可以認爲是一個文件夾
Method method = null;
try {
method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
} catch (NoSuchMethodException | SecurityException e1) {
e1.printStackTrace();
}
// 獲取方法的訪問權限以便寫回
boolean accessible = method.isAccessible();
try {
method.setAccessible(true);
// 獲取系統類加載器
URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
URL url = jarFile.toURI().toURL();
method.invoke(classLoader, url);
} catch (Exception e) {
e.printStackTrace();
} finally {
method.setAccessible(accessible);
}
}
}
java動態加載jar文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.