Java代码如何循环遍历类路径下所有类呢?

乔欣 Java经验 发布时间:2023-03-21 20:44:53 阅读数:9839 1
下文笔者讲述使用java代码获取指定路径下所有类的方法分享,如下所示

获取指定路径下类所有类信息

获取指定路径下的类信息:
    可以使用遍历文件夹的方式,获取指定路径下的所有类信息
例:获取指定路径下所有类的示例
public class WalkClasspathAllClasses {
 public static void main(String[] args) throws URISyntaxException, IOException {
	list<URL> urls = new ArrayList<>();
	//获取Classpath
	if (WalkClasspathAllClasses.class.getClassLoader() instanceof URLClassLoader) {
		Collections.addAll(urls, ((URLClassLoader) WalkClasspathAllClasses.class.getClassLoader()).getURLs());
	} else {
		for (String s : System.getProperty("java.class.path").split(";")) {
			urls.add(new File(s).toURI().toURL());
		}
  }
  //遍历所有类
  walkAllClasses(urls).forEach(System.out::println);
}

private static Set<String> walkAllClasses(List<URL> urls) throws URISyntaxException, IOException {
	Set<String> classes = new HashSet<>();
	for (URL url : urls) {
		if (url.toURI().getScheme().equals("file")) {//判断Scheme是不是file
			File file = new File(url.toURI());
			if (!file.exists()) continue;//是存在
			if (file.isDirectory()) {//如果是目录
				Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {//遍历所有文件
					@Override
					public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
						if (path.toFile().getName().endsWith(".class")) {//判断是否为class后缀
							//去除路径截取包名
							String substring = path.toFile().getAbsolutePath().substring(file.getAbsolutePath().length());
							if (substring.startsWith(File.separator)) {
								substring = substring.substring(1);
							}
							substring = substring.substring(0, substring.length() - 6);//去掉后缀
							classes.add(substring.replace(File.separator, "."));//把路径替换为.
						}
						return super.visitFile(path, attrs);
					}
				});
			} else if (file.getName().endsWith(".jar")) {//如果是jar包
				JarFile jarFile = new JarFile(file);
				Enumeration<JarEntry> entries = jarFile.entries();
				while (entries.hasMoreElements()) {//遍历所有文件
					JarEntry jarEntry = entries.nextElement();
					if (!jarEntry.getName().endsWith(".class")) continue;//判断后缀是否为class
					String replace = jarEntry.getName().replace("/", ".");//把路径替换为.
					classes.add(replace.substring(0, replace.length() - 6));//去掉后缀
				}
			}
		}
	}
	return classes;
 }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202303/16794028396124.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者