package com.load;
import org.junit.Test;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* success
*/
public class Client {
public URLClassLoader classLoader;
@Test
public void loadInterJar() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
String domain = "http://localhost/plugin.jar";
//jar 资源协议
String jarUrl="jar:"+domain+"!/";
//远程jar文件
URL jar = new URL(jarUrl);
//url类加载器
classLoader = new URLClassLoader(new URL[]{jar});
//jar资源文件的链接
JarURLConnection jarConn = (JarURLConnection) jar.openConnection();
//获取jar文件 下载下来 下载到临时文件中 window时temp中 获取到下载的jar 对象
JarFile jarFile = jarConn.getJarFile();
initJarFile(jarFile);
}
public void initJarFile(JarFile jarFile) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
//C:\Users\XIAOJI~2\AppData\Local\Temp\jar_cache3537854604629475378.tmp
// System.out.println(jarFile.getName());
String basePackage="com.load.plugin";
Set<Class> classes = new HashSet<>();
Class<?> clazz;
String pkgPath = basePackage.replace(".", "/");
Enumeration<JarEntry> entries = jarFile.entries();
//判断是否有子节点
//遍历jar中所有的文件
while (entries.hasMoreElements()) {
//jar的实体
JarEntry jarEntry = entries.nextElement();
String name = jarEntry.getName();
//打印出所有的文件路径+名称
// System.out.println(name);
//去除第一个位置的'/'
if (name.charAt(0) == '/') {
name = name.substring(1);
}
//去除文件夹 和非class 的文件
if (jarEntry.isDirectory() || !name.startsWith(pkgPath) || !name.endsWith(".class")) {
continue;
}
//得到要装在类的名字 去除class结尾 例如 com.load.plugin.IFunction.class ==> com.load.plugin.IFunction
String className = name.substring(0, name.length() - 6);
//将'/'转成'.'
className = className.replace("/", ".");
//加载的类欸名称
System.out.println(className);
//加载类 后可以通过名字动态new
clazz =classLoader.loadClass(className);
System.out.println(IFunction.class.isAssignableFrom(clazz));
if (clazz != null && !clazz.isInterface() && IFunction.class.isAssignableFrom(clazz)) {
classes.add(clazz);
}
}
System.out.println(classes);
createObject(classes);
System.out.println();
}
public void createObject(Set<Class> classes) throws InstantiationException, IllegalAccessException {
Map<String, IFunction> functions = new ConcurrentHashMap<String, IFunction>();
if (classes != null && classes.size() > 0) {
for (Class clazz : classes) {
//实例化每一个类
IFunction function = (IFunction) clazz.newInstance();
//String name = function.getName();
functions.put("test", function);
}
}
//调用类方法
IFunction test = functions.get("test");
test.test();
}
}
自定义了加载器,实现加载jar包,进入本地jvm调用
最新推荐文章于 2023-04-24 16:18:20 发布