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.apachemons.lang3.StringUtils");
Object instance = wInstance();
Object strip = DeclaredMethod("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 (ists() == false) {
System.out.println("jar file not found.");
return;
}
//获取类加载器的addURL⽅法,准备动态调⽤
Method method = null;
try {
method = DeclaredMethod("addURL", URL.class);
} catch (NoSuchMethodException | SecurityException e1) {
e1.printStackTrace();
}
// 获取⽅法的访问权限,保存原始值
boolean accessible = method.isAccessible();
try {
//修改访问权限为可写
if (accessible == false) {
method.setAccessible(true);
}
/
/ 获取系统类加载器
URLClassLoader classLoader = (URLClassLoader) SystemClassLoader();
//获取jar⽂件的url路径
java.URL url = URI().toURL();
//jar路径加⼊到系统url路径⾥repository文件夹可以删除吗
method.invoke(classLoader, url);
} catch (Exception e) {
e.printStackTrace();
} finally {
//回写访问权限
method.setAccessible(accessible);
}
}
参考⽂章:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。