查找指定路径下面的类

130 阅读1分钟
根据指定的包名,然后获取包下面所有的类:
思路,去到指定的包下面查找所有的文件,再将class文件找到,转化class文件的路径

public class
Test{
static
String
path
=
"test"
;
public static void
main
(String[] args)
throws
IOException {

//如果是包含 . 需要将.改为/ 因为 这里指的是文件路径
if
(
path
.contains(
"."
)){
path
=
path
.replace(
"."
,
"/"
)
;
}
//获取路径下面所有的包
Enumeration<URL> resources = TestFactory.
class
.getClassLoader().getResources(
path
)
;

//遍历 所有的路径
while
(resources.hasMoreElements()){
//获取包的真实路径
String fileRealPath = resources.nextElement().getPath()
;

File file =
new
File(fileRealPath)
;
if
(file.isDirectory()){
getFilesByPath(file)
;
}

}
}

public static void
getFilesByPath
(File f){
File[] files = f.listFiles()
;
for
(File file : files) {
if
(file.isFile()){
//例如 是这个样子 E:\idea_workplace\workSet\myspring\target\classes\test\mylo\aop\Log.class
//获取到了全路径之后 的事情就比较好办了,我们就截取先前路径后面的字符串就OK
//例如 test\mylo\aop\Log.class
// 把 \ 换点 . 去掉 .class 就是类全名了
if
(file.getName().endsWith(
".class"
)){
String fullPath = file.getAbsolutePath()
;
//先前我们把path里面的 . 转换为了/ 这个时候需要转为了 \
if
(
path
.contains(
"/"
)){
path
=
path
.replace(
"/"
,
"
\\
"
)
;
}

int
indexOfPath = fullPath.indexOf(
path
)
;

//test\mylo\aop\Log.class
String classPath = fullPath.substring(indexOfPath)
;
int
lastIndexOfPoint = classPath.lastIndexOf(
"."
)
;
String finalName = classPath.substring(
0
,
lastIndexOfPoint)
;
//test\mylo\aop\Log
// System.out.println(finalName);
//将\转化为
finalName = finalName.replaceAll(
"
\\\\
"
,
"."
)
;
System.
out
.println(finalName)
;
}
}
else if
(file.isDirectory()){
getFilesByPath(file)
;
}
}

}
}

更多技术资讯可关注:gzitcast