A brilliant job, perfect in nature -- implementation of packet scanning

Keywords: Java

I believe that when you learn Java to a certain depth, you will encounter a problem - package scanning

  • Next, I will talk about the self-realization of packet scanning.
  • Packet scanning should pay attention to several issues, the general package inside the file
  • And the files in the jar package
  • And when there is a directory in the package, we need to make recursive calls.
  • Resolve the files in the directory
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);
			} else if (file.isFile()) {
				dealClassFile(rootPackage + "." + curFile.getName(), 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();
		}
	}
	
}

The readability of this tool is good. You can read it and use it directly.
If you think it's OK, can you give me a compliment?
Ha ha ha ha ha ha ha

Posted by mike_at_hull on Sat, 05 Oct 2019 16:54:00 -0700