jar中查找类

back_recharge
zhangshanxue 2019-10-09 15:12:11 +08:00
parent c6cf91aa70
commit 981191c053
2 changed files with 71 additions and 0 deletions

View File

@ -502,6 +502,7 @@ public class ProtocolsManager implements ProtocolsAbstract {
try
{
ClassLoaderHelper.findLocalClass(pck, BaseHandler.class, classLoader, handlers);
ClassLoaderHelper.findClassJar(pck, BaseHandler.class, classLoader, handlers);
handlers.forEach(hand ->
{
BaseHandler baseHandler = null;

View File

@ -1,10 +1,16 @@
package com.ljsd.jieling.util;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Description: des
@ -77,4 +83,68 @@ public class ClassLoaderHelper {
return filterclass.isAssignableFrom(clazz);
}
/**
* jar
*/
public static void findClassJar(final String packName, Class<?> classinterface, ClassLoader classLoader, List<Class<?>> classes)
{
String pathName = packName.replace(".", "/");
JarFile jarFile;
try
{
URL url = classLoader.getResource(pathName);
JarURLConnection jarURLConnection = (JarURLConnection)url.openConnection();
jarFile = jarURLConnection.getJarFile();
}
catch(IOException |NullPointerException e)
{
return;
}
Enumeration<JarEntry> jarEntries = jarFile.entries();
while(jarEntries.hasMoreElements())
{
JarEntry jarEntry = jarEntries.nextElement();
String jarEntryName = jarEntry.getName();
if(jarEntryName.contains(pathName) && !jarEntryName.equals(pathName + "/"))
{
if(jarEntry.isDirectory())
{
String clazzName = jarEntry.getName().replace("/", ".");
int endIndex = clazzName.lastIndexOf(".");
String prefix = null;
if(endIndex > 0)
{
prefix = clazzName.substring(0, endIndex);
}
findClassJar(prefix, classinterface,classLoader,classes);
}
if(jarEntry.getName().endsWith(".class"))
{
Class<?> clazz = null;
try
{
clazz = classLoader.loadClass(jarEntry.getName().replace("/", ".").replace(".class", ""));
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
if(clazz == null)
{
return;
}
if(filter(clazz, classinterface))
{
classes.add(clazz);
}
}
}
}
}
}