自定义类加载器
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* 自定义类加载器
*/
public class MyClassLoader extends ClassLoader {
public JarFile jarFile;
public ClassLoader parent;
public MyClassLoader(JarFile jarFile) {
super(Thread.currentThread().getContextClassLoader());
this.parent = Thread.currentThread().getContextClassLoader();
this.jarFile = jarFile;
}
public MyClassLoader(JarFile jarFile, ClassLoader parent) {
super(parent);
this.parent = parent;
this.jarFile = jarFile;
}
public String classNameToJarEntry(String name){
String s = name.replaceAll("\\.", "\\/");
StringBuilder stringBuilder = new StringBuilder(s);
stringBuilder.append(".class");
return stringBuilder.toString();
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
try {
Class c = null;
if (null != jarFile) {
String jarEntryName = classNameToJarEntry(name);
JarEntry entry = jarFile.getJarEntry(jarEntryName);
if (null != entry) {
InputStream is = jarFile.getInputStream(entry);
int availableLen = is.available();
int len = 0;
byte[] bt1 = new byte[availableLen];
while (len < availableLen) {
len += is.read(bt1, len, availableLen - len);
}
c = defineClass(name, bt1, 0, bt1.length);
} else {
if (parent != null) {
return parent.loadClass(name);
}
}
}
return c;
} catch (IOException e) {
throw new ClassNotFoundException("Class " + name + " not found.");
}
}
@Override
public InputStream getResourceAsStream(String name) {
InputStream is = null;
try {
if (null != jarFile) {
JarEntry entry = jarFile.getJarEntry(name);
if (entry != null) {
is = jarFile.getInputStream(entry);
}
if (is == null) {
is = super.getResourceAsStream(name);
}
}
} catch (IOException e) {
// logger.error(e.getMessage());
System.out.println(e.getMessage());
}
return is;
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
MyClassLoader classLoader = new MyClassLoader(new JarFile(new File("F:\\桌面\\zqwl.jar"))); //自定义ClassLoader来加载jar文件
Enumeration<JarEntry> entries = classLoader.jarFile.entries();
while (entries.hasMoreElements()) {
String name = entries.nextElement().getName();
System.out.println("name: " + name);
}
Class clazz1 = classLoader.loadClass("ProcessUtil"); //类名(包名+类名)
Object obj1 = clazz1.newInstance();
Method method1 = clazz1.getDeclaredMethod("getColltion", String.class); //调用的方法名 及方法的参数类型
Object[] objsA = new Object[1]; //传入要调用的方法的具体参数
objsA[0] = new String("%7B%22IMEI%22%3A866250061587386%2C%22time%22%3A%222023-03-15+16%3A20%3A34%22%2C%22k0%22%3A23.2%2C%22k1%22%3A0.0%7D");
String s = method1.invoke(obj1, objsA).toString(); //获取调用方法的返回值 obj1 实列对象 objsA 具体参数
}