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遍历包中所有类的更多相关文章

  1. 关于java同步包中ConcurrentLinkedQueue类的深入分析与理解

    一,官方描写叙述 一个基于连接节点的无界线程安全队列.这个队列的顺序是先进先出.队列头部的元素是留在队列中时间最长的,队列尾部的元素是留在队列中时间最短的.新元素被插入到元素的尾部,队列从队列的头部检 ...

  2. Java遍历包中所有类方法注解

    import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.lang.annotat ...

  3. 27 Java动态加载第三方jar包中的类

    我加载的方法是://参数fileName是jar包的路径,processorName 是业务类的包名+类名public static A load(String fileName, String pr ...

  4. 集合框架的类和接口均在java.util包中。 任何对象加入集合类后,自动转变为Object类型,所以在取出的时候,需要进行强制类型转换。

    集合框架的类和接口均在java.util包中. 任何对象加入集合类后,自动转变为Object类型,所以在取出的时候,需要进行强制类型转换.

  5. Java日期时间API系列6-----Jdk8中java.time包中的新的日期时间API类

    因为Jdk7及以前的日期时间类的不方便使用问题和线程安全问题等问题,2005年,Stephen Colebourne创建了Joda-Time库,作为替代的日期和时间API.Stephen向JCP提交了 ...

  6. Java日期时间API系列13-----Jdk8中java.time包中的新的日期时间API类,时间类转换,Date转LocalDateTime,LocalDateTime转Date等

    从前面的系列博客中可以看出Jdk8中java.time包中的新的日期时间API类设计的很好,但Date由于使用仍非常广泛,这就涉及到Date转LocalDateTime,LocalDateTime转D ...

  7. Java日期时间API系列19-----Jdk8中java.time包中的新的日期时间API类,ZonedDateTime与ZoneId和LocalDateTime的关系,ZonedDateTime格式化和时区转换等。

    通过Java日期时间API系列6-----Jdk8中java.time包中的新的日期时间API类中时间范围示意图:可以很清晰的看出ZonedDateTime相当于LocalDateTime+ZoneI ...

  8. Java日期时间API系列8-----Jdk8中java.time包中的新的日期时间API类的LocalDate源码分析

    目录 0.前言 1.TemporalAccessor源码 2.Temporal源码 3.TemporalAdjuster源码 4.ChronoLocalDate源码 5.LocalDate源码 6.总 ...

  9. Java日期时间API系列11-----Jdk8中java.time包中的新的日期时间API类,使用java8日期时间API重写农历LunarDate

    通过Java日期时间API系列7-----Jdk8中java.time包中的新的日期时间API类的优点,java8具有很多优点,现在网上查到的农历转换工具类都是基于jdk7及以前的类写的,下面使用ja ...

随机推荐

  1. Unicode中的BOM

    BOM简述 BOM是byte order mark的缩写,在UTF-16和UTF-32中需要使用BOM来区分字节的顺序,因为我们目前的CPU有两种系列,一种是大端模式,一种是小端模式(我们常用的电脑手 ...

  2. 【spring boot】spring boot @ConditionalOnxxx相关注解总结

    参考地址:https://blog.csdn.net/win7system/article/details/54377471 使用场景:在自动解析封装配置文件中的配置完成自动注入spring的时候 例 ...

  3. appium+python自动化50-生成定位对象模板templet(jinja2)

    前言 每次自己写pageobject定位元素对象太繁琐,格式都差不多,只是换个定位方法,这种就可以才有模板的方式,批量生成pageobject定位元素对象的模板 python里面生成模板有两个模块可以 ...

  4. nginx配置rewrite总结

    1.rewrite regex replacement [flag] 2.flag为break时,url重写后,直接使用当前资源,不在执行location里其他语句,完成本次请求,地址栏url不变. ...

  5. jQuery 当页面 ID 不唯一时,寻找元素

     $(需要寻找元素的父层).find(元素ID,元素Class) 

  6. UML类图几种关系的总结 【转】

    在UML类图中,常见的有以下几种关系:泛化(Generalization),  实现(Realization),关联(Association),聚合(Aggregation),组合(Compositi ...

  7. [Angular] AfterContentChecked && AfterViewChecked

    AfterContentChecked & AfterViewChecked are called after 'OnChanges' lifecycle. And each time 'ng ...

  8. Qracle、Sql server 、mysql查询练习题

    1. select * from emp; 2. select empno, ename, job from emp; 3. select empno 编号, ename 姓名, job 工作 fro ...

  9. CF无法全屏怎么办

    方法1:把桌面的分辨率调成800X600,然后运行CF就全屏了,接着再退出游戏,把桌面重新调回原来的分辨率. 方法2:在运行中输入regedit.可以打开打开注册表编辑器,定位到HKEY_LOCAL_ ...

  10. js 因加入form导致两个table之间出现空白问题

    在<FORM>中加CSS <table> ....... </table> <form style="padding:0; margin:0;&qu ...