import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* 加載jar包 到項目中
* @param jarPath jar包路徑
*/
protected 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);
}
}