1. 服务调用方
调用方是poi 3.17 ,被调用方是poi-4.1.2版本
package com.demo;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Demo {
public static void main(String[] args) throws IOException {
ClassLoaderUtil.loadJarPath("F:\\IdeaProject1\\hutool-excel-demo2\\lib");
System.err.println(Thread.currentThread().getContextClassLoader());
Class clazz = null;
try {
clazz = Thread.currentThread().getContextClassLoader().loadClass("main.java.com.auto.create.ExcelUtils2");
System.err.println(clazz);
Method method = clazz.getMethod("demo",null);
System.err.println(Thread.currentThread().getContextClassLoader());
method.invoke(clazz,null);
System.err.println(Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
2. 自定义classLoader
package main.java.com.auto.create;
import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class MyJarClassLoader extends URLClassLoader {
private static URL[] tempUrl;
private URL[] allUrl;
public MyJarClassLoader(String[] paths) {
this(paths, MyJarClassLoader.class.getClassLoader());
}
public void addClass(String className) {
try {
classMap.put(className, Class.forName(className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public MyJarClassLoader(String[] paths, ClassLoader parent) {
super(getURLs(paths), parent);
allUrl = tempUrl;
}
public MyJarClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
private static URL[] getURLs(String[] paths) {
if (null == paths || 0 == paths.length) {
throw new RuntimeException("jar包路径不能为空.");
}
List<String> dirs = new ArrayList<String>();
for (String path : paths) {
dirs.add(path);
MyJarClassLoader.collectDirs(path, dirs);
}
List<URL> urls = new ArrayList<URL>();
for (String path : dirs) {
urls.addAll(doGetURLs(path));
}
URL[] threadLocalurls = urls.toArray(new URL[0]);
tempUrl = threadLocalurls;
return threadLocalurls;
}
private static void collectDirs(String path, List<String> collector) {
if (null == path || "".equalsIgnoreCase(path)) {
return;
}
File current = new File(path)