Java遍历包中所有类
PackageUtil 类
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile; /**
* 获取包中所有的类
* @author
*
*/
public class PackageUtil { public static void main(String[] args) throws Exception {
String packageName = "com.wang.vo.request.hotel";
// List<String> classNames = getClassName(packageName);
List<String> classNames = getClassName(packageName, false);
if (classNames != null) {
for (String className : classNames) {
System.out.println(className);
}
}
} /**
* 获取某包下(包括该包的所有子包)所有类
*
* @param packageName
* 包名
* @return 类的完整名称
*/
public static List<String> getClassName(String packageName) {
return getClassName(packageName, true);
} /**
* 获取某包下所有类
*
* @param packageName
* 包名
* @param childPackage
* 是否遍历子包
* @return 类的完整名称
*/
public static List<String> getClassName(String packageName, boolean childPackage) {
List<String> fileNames = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String packagePath = packageName.replace(".", "/");
URL url = loader.getResource(packagePath);
if (url != null) {
String type = url.getProtocol();
if (type.equals("file")) {
fileNames = getClassNameByFile(url.getPath(), null, childPackage);
} else if (type.equals("jar")) {
fileNames = getClassNameByJar(url.getPath(), childPackage);
}
} else {
fileNames = getClassNameByJars(((URLClassLoader) loader).getURLs(), packagePath, childPackage);
}
return fileNames;
} /**
* 从项目文件获取某包下所有类
*
* @param filePath
* 文件路径
* @param className
* 类名集合
* @param childPackage
* 是否遍历子包
* @return 类的完整名称
*/
private static List<String> getClassNameByFile(String filePath, List<String> className, boolean childPackage) {
List<String> myClassName = new ArrayList<>();
File file = new File(filePath);
File[] childFiles = file.listFiles();
for (File childFile : childFiles) {
if (childFile.isDirectory()) {
if (childPackage) {
myClassName.addAll(getClassNameByFile(childFile.getPath(), myClassName, childPackage));
}
} else {
String childFilePath = childFile.getPath();
if (childFilePath.endsWith(".class")) {
childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + ,
childFilePath.lastIndexOf("."));
childFilePath = childFilePath.replace("\\", ".");
myClassName.add(childFilePath);
}
}
} return myClassName;
} /**
* 从jar获取某包下所有类
*
* @param jarPath
* jar文件路径
* @param childPackage
* 是否遍历子包
* @return 类的完整名称
*/
private static List<String> getClassNameByJar(String jarPath, boolean childPackage) {
List<String> myClassName = new ArrayList<>();
String[] jarInfo = jarPath.split("!");
String jarFilePath = jarInfo[].substring(jarInfo[].indexOf("/"));
String packagePath = jarInfo[].substring();
try {
JarFile jarFile = new JarFile(jarFilePath);
Enumeration<JarEntry> entrys = jarFile.entries();
while (entrys.hasMoreElements()) {
JarEntry jarEntry = entrys.nextElement();
String entryName = jarEntry.getName();
if (entryName.endsWith(".class")) {
if (childPackage) {
if (entryName.startsWith(packagePath)) {
entryName = entryName.replace("/", ".").substring(, entryName.lastIndexOf("."));
myClassName.add(entryName);
}
} else {
int index = entryName.lastIndexOf("/");
String myPackagePath;
if (index != -) {
myPackagePath = entryName.substring(, index);
} else {
myPackagePath = entryName;
}
if (myPackagePath.equals(packagePath)) {
entryName = entryName.replace("/", ".").substring(, entryName.lastIndexOf("."));
myClassName.add(entryName);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return myClassName;
} /**
* 从所有jar中搜索该包,并获取该包下所有类
*
* @param urls
* URL集合
* @param packagePath
* 包路径
* @param childPackage
* 是否遍历子包
* @return 类的完整名称
*/
private static List<String> getClassNameByJars(URL[] urls, String packagePath, boolean childPackage) {
List<String> myClassName = new ArrayList<>();
if (urls != null) {
for (int i = ; i < urls.length; i++) {
URL url = urls[i];
String urlPath = url.getPath();
// 不必搜索classes文件夹
if (urlPath.endsWith("classes/")) {
continue;
}
String jarPath = urlPath + "!/" + packagePath;
myClassName.addAll(getClassNameByJar(jarPath, childPackage));
}
}
return myClassName;
}
}
由于我们并不确定jar包生成时采用的哪种方式,如果采用默认生成jar包的方式,那我们通过Thread.currentThread().getContextClassLoader().getResource()是获取不到的,因此增加了从所有jar包中搜索提供的包域名,这样功能就完善了很多。
转载至https://www.2cto.com/kf/201211/169865.html
Java遍历包中所有类的更多相关文章
- 关于java同步包中ConcurrentLinkedQueue类的深入分析与理解
一,官方描写叙述 一个基于连接节点的无界线程安全队列.这个队列的顺序是先进先出.队列头部的元素是留在队列中时间最长的,队列尾部的元素是留在队列中时间最短的.新元素被插入到元素的尾部,队列从队列的头部检 ...
- Java遍历包中所有类方法注解
import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.lang.annotat ...
- 27 Java动态加载第三方jar包中的类
我加载的方法是://参数fileName是jar包的路径,processorName 是业务类的包名+类名public static A load(String fileName, String pr ...
- 集合框架的类和接口均在java.util包中。 任何对象加入集合类后,自动转变为Object类型,所以在取出的时候,需要进行强制类型转换。
集合框架的类和接口均在java.util包中. 任何对象加入集合类后,自动转变为Object类型,所以在取出的时候,需要进行强制类型转换.
- Java日期时间API系列6-----Jdk8中java.time包中的新的日期时间API类
因为Jdk7及以前的日期时间类的不方便使用问题和线程安全问题等问题,2005年,Stephen Colebourne创建了Joda-Time库,作为替代的日期和时间API.Stephen向JCP提交了 ...
- Java日期时间API系列13-----Jdk8中java.time包中的新的日期时间API类,时间类转换,Date转LocalDateTime,LocalDateTime转Date等
从前面的系列博客中可以看出Jdk8中java.time包中的新的日期时间API类设计的很好,但Date由于使用仍非常广泛,这就涉及到Date转LocalDateTime,LocalDateTime转D ...
- Java日期时间API系列19-----Jdk8中java.time包中的新的日期时间API类,ZonedDateTime与ZoneId和LocalDateTime的关系,ZonedDateTime格式化和时区转换等。
通过Java日期时间API系列6-----Jdk8中java.time包中的新的日期时间API类中时间范围示意图:可以很清晰的看出ZonedDateTime相当于LocalDateTime+ZoneI ...
- Java日期时间API系列8-----Jdk8中java.time包中的新的日期时间API类的LocalDate源码分析
目录 0.前言 1.TemporalAccessor源码 2.Temporal源码 3.TemporalAdjuster源码 4.ChronoLocalDate源码 5.LocalDate源码 6.总 ...
- Java日期时间API系列11-----Jdk8中java.time包中的新的日期时间API类,使用java8日期时间API重写农历LunarDate
通过Java日期时间API系列7-----Jdk8中java.time包中的新的日期时间API类的优点,java8具有很多优点,现在网上查到的农历转换工具类都是基于jdk7及以前的类写的,下面使用ja ...
随机推荐
- 怎么设置IDEA,去除单词拼写检查,或者添加自定义的单词
如图所示,添加自定义的单词,这样IDEA检查的时候,就不会报错了.估计默认是根据英文单词来释义的.
- 关于TagHelper的那些事情——Microsoft.AspNet.Mvc.TagHelpers介绍
写在开始 在上一篇文章中,简单介绍了什么是TagHelper,怎么使用它.接下来我会简单介绍一下微软随着ASP.NET5一起发布的TagHelpers.它们分别是: AnchorTagHelper C ...
- iOS: 工具栏控件UIToolBar和工具栏按钮控件UIBarButtonItem的使用
一.工具栏控件:UIToolBar:UIView 介绍: ToolBar工具栏是视图View的属性,可以在工具栏上添加工具栏按钮Bar Button Item(可以是自定义的Custom.也可以是系统 ...
- Vmware 14.0 版本中安装Ubuntu 17.10版本无法调整分辨率的问题
装完ubuntu后发现在vmware中选择了查看-自动调整大小-自适应客户机,虚拟机也无法随着窗口大小来切换分辨率,其实是因为WAYLAND限制了. 1. 先安装vim sudo apt-get in ...
- 把mysql的数据导出成txt
把mysql的数据导出成txt select a from b into outfile '/sqlfile/a.txt'; my.ini里需要设置secure_file_priv = d:/sqlf ...
- Windows录音API学习笔记
Windows录音API学习笔记 结构体和函数信息 结构体 WAVEINCAPS 该结构描述了一个波形音频输入设备的能力. typedef struct { WORD wMid; 用于波形 ...
- Solidworks的Toolbox拖出来的零件另存也没用,重新打开之后被自动替换怎么办
工具-选项-系统选项-异型孔向导,取消勾选"将此文件夹设为Toolbox零部件的默认搜索位置" 这样把Toolbox的零部件另存之后,就可以修改,比如添加草图和特征,然后另存之 ...
- Python监控进程性能数据并画图保存为PDF文档
引言 利用psutil模块(https://pypi.python.org/pypi/psutil/),可以很方便的监控系统的CPU.内存.磁盘IO.网络带宽等性能參数,下面是否代码为监控某个特定程序 ...
- Android ANR发生原因总结
ANR(Application Not Responding) Android系统中应用无响应 是Android系统中比较常见的问题,当出现ANR时一般情况会弹出一个带有以下文字的对话框提示: Act ...
- C++11 std::async 包装实体店::packaged_task
更好的方式 C++11中提供了操作多线程的高层次特性. std::packaged_task 包装的是一个异步操作,相当与外包任务,好比我大阿里把电话客服外包给某某公司. std::future 提供 ...