build: 兼容jdk版本的加载jar

This commit is contained in:
CaptainB 2022-04-06 18:29:13 +08:00 committed by 刘瑞斌
parent 299f81a0b9
commit d57484f57f
1 changed files with 12 additions and 18 deletions

View File

@ -44,26 +44,20 @@ public class MockScriptEngineUtils {
} }
public void loadJar(String jarPath) throws Exception { public void loadJar(String jarPath) throws Exception {
File jarFile = new File(jarPath);
// 从URLClassLoader类中获取类所在文件夹的方法jar也可以认为是一个文件夹
Method method = null;
try { try {
method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); ClassLoader classLoader = ClassLoader.getSystemClassLoader();
} catch (NoSuchMethodException | SecurityException e1) { try {
e1.printStackTrace(); Method method = classLoader.getClass().getDeclaredMethod("addURL", URL.class);
} method.setAccessible(true);
// 获取方法的访问权限以便写回 method.invoke(classLoader, new File(jarPath).toURI().toURL());
boolean accessible = method.isAccessible(); } catch (NoSuchMethodException e) {
try { Method method = classLoader.getClass()
method.setAccessible(true); .getDeclaredMethod("appendToClassPathForInstrumentation", String.class);
// 获取系统类加载器 method.setAccessible(true);
URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); method.invoke(classLoader, jarPath);
URL url = jarFile.toURI().toURL(); }
method.invoke(classLoader, url);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); LogUtil.error(e);
} finally {
method.setAccessible(accessible);
} }
} }