巧夺天工,浑然天成————实现包扫描
相信大家学习Java到一定深度的时候,就会碰到一个问题————包扫描
- 接下来讲讲包扫描的自我实现
- 包扫描里面要注意的几个问题,一般的包里面的文件
- 以及jar包里面的文件
- 还有当包里面有目录的时候,我们需要进行递归调用
- 将目录里面的文件再进行解析
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public abstract class PackageScanner {
public abstract void dealClass(Class<?> klass);
private void dealClassFile(String rootPackage, File file) {
String fileName = file.getName();
if (fileName.endsWith(".class")) {
fileName = fileName.replace(".class", "");
try {
Class<?> klass = Class.forName(rootPackage + "." + fileName);
dealClass(klass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
private void dealDirectory(String rootPackage, File curFile) {
File[] fileList = curFile.listFiles();
for (File file : fileList) {
if (file.isDirectory()) {
dealDirectory(rootPackage + "." + file.getName(), file);
} else if (file.isFile()) {
dealClassFile(rootPackage, file);
}
}
}
private void dealJarPackage(URL url) {
try {
JarURLConnection connection = (JarURLConnection) url.openConnection();
JarFile jarFile = connection.getJarFile();
Enumeration<JarEntry> jarEntries = jarFile.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jar = jarEntries.nextElement();
if(jar.isDirectory() || !jar.getName().endsWith(".class")) {
continue;
}
String jarName = jar.getName();
jarName = jarName.replace(".class", "");
jarName = jarName.replace("/", ".");
try {
Class<?> klass = Class.forName(jarName);
dealClass(klass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void packageScanner(String packageName) {
String rootPackage = packageName;
packageName = packageName.replace(".", "/");
URL url = Thread.currentThread().getContextClassLoader().getResource(packageName);
try {
if (url.getProtocol().equals("file")) {
URI uri = url.toURI();
File root = new File(uri);
dealDirectory(rootPackage, root);
} else {
dealJarPackage(url);
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
*这个工具可读性还是不错的,各位可以读懂直接拿来用哦,
如果觉得还行的话,可以给个赞吗
哈哈哈哈哈*