package
core;
import
java.io.File;
import
java.io.FileFilter;
import
java.io.IOException;
import
java.net.JarURLConnection;
import
java.net.URL;
import
java.net.URLDecoder;
import
java.util.ArrayList;
import
java.util.Enumeration;
import
java.util.List;
import
java.util.Set;
import
java.util.jar.JarEntry;
import
java.util.jar.JarFile;
/**
* @Author : L_C
* @Date Created in 9:28 2019/8/26
* @Description :
* @Modified :
*/
public
class
ClassScanner {
public
static
List<Class<?>> classes =
new
ArrayList<>();
public
static
List<Class<?>> scanClasses(String packageName)
throws
IOException, ClassNotFoundException {
List<Class<?>> classList =
new
ArrayList<>();
String path = packageName.replace(
"."
,
"/"
);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> resources = classLoader.getResources(path);
while
(resources.hasMoreElements()){
URL resource = resources.nextElement();
if
(resource.getProtocol().contains(
"jar"
)){
JarURLConnection jarURLConnection = (JarURLConnection)resource.openConnection();
String jarFilePath = jarURLConnection.getJarFile().getName();
classList.addAll(getClassesFromJar(jarFilePath,path));
}
else
{
String filePath = URLDecoder.decode(resource.getPath(),
"UTF-8"
);
System.out.println(filePath);
boolean
recursive =
true
;
classList.addAll( findAndAddClassesInPackageByFile(packageName, filePath, recursive));
}
}
return
classList;
}
private
static
List<Class<?>> getClassesFromJar(String jarFilePath,String path)
throws
IOException, ClassNotFoundException {
JarFile jarFile =
new
JarFile(jarFilePath);
Enumeration<JarEntry> jarEntries = jarFile.entries();
while
(jarEntries.hasMoreElements()){
JarEntry jarEntry = jarEntries.nextElement();
String entryName = jarEntry.getName();
if
(entryName.startsWith(path)&&entryName.endsWith(
".class"
)){
String classFullName = entryName.replace(
"/"
,
"."
).substring
(
0
,entryName.length()-
6
);
classes.add(Class.forName(classFullName));
}
}
return
classes;
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
*/
public
static
List<Class<?>> findAndAddClassesInPackageByFile(String packageName, String packagePath,
final
boolean
recursive ) {
File dir =
new
File(packagePath);
if
(!dir.exists() || !dir.isDirectory()) {
return
null
;
}
File[] dirfiles = dir.listFiles(
new
FileFilter() {
public
boolean
accept(File file) {
return
(recursive && file.isDirectory()) || (file.getName().endsWith(
".class"
));
}
});
for
(File file : dirfiles) {
if
(file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName +
"."
+ file.getName(), file.getAbsolutePath(), recursive);
}
else
{
String className = file.getName().substring(
0
, file.getName().length() -
6
);
try
{
classes.add(
Thread.currentThread().getContextClassLoader().loadClass(packageName +
'.'
+ className));
}
catch
(ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return
classes;
}
}