java扫描目录下的文件_Java扫描包路径下的类文件

前言:

在写代码的时候,经常会遇到一些配置包路径的代码,然后框架根据提供的包路径进行扫描,比如Spring。所以这里自己去实现一下扫描包路径下类的代码。

在看资料的过程中,总结出了两个不同的扫描方式,第一种是在扫描src下的包,这时候使用文件系统就可以获取到包下面的类文件;第二种是扫描jar包中的包路径,这时候需要使用JarURLConnection类了,这个可以将Jar包中目标包路径下的文件生成一个个JarEntity,遍历生成的JarEntitys就可以获取目标类文件。

代码实现:

public class Utils {

//从包路径下扫描public static Set

getClasses(String packagePath) {

Set res = new HashSet<>();

String path =

packagePath.replace(".", "/");

URL url = Thread.currentThread().getContextClassLoader().getResource(path);

if (url == null) {

System.out.println(packagePath

+ "

is not exit");

return res;

}

String protocol =

url.getProtocol();

if ("jar".equalsIgnoreCase(protocol))

{

try {

res.addAll(getJarClasses(url,

packagePath));

} catch (IOException e)

{

e.printStackTrace();

return res;

}

} else if ("file".equalsIgnoreCase(protocol))

{

res.addAll(getFileClasses(url,

packagePath));

}

return res;

}

//获取file路径下的class文件private static Set

getFileClasses(URL url, String packagePath) {

Set res = new HashSet<>();

String filePath =

url.getFile();

File dir = new File(filePath);

String[] list = dir.list();

if (list == null) return res;

for (String classPath : list) {

if (classPath.endsWith(".class")) {

classPath =

classPath.replace(".class", "");

try {

Class>

aClass = Class.forName(packagePath + "." + classPath);

res.add(aClass);

} catch (ClassNotFoundException

e) {

e.printStackTrace();

}

} else {

res.addAll(getClasses(packagePath

+ "."

+

classPath));

}

}

return res;

}

//使用JarURLConnection类获取路径下的所有类private static Set

getJarClasses(URL url, String packagePath) throws IOException {

Set res = new HashSet<>();

JarURLConnection conn =

(JarURLConnection) url.openConnection();

if (conn != null) {

JarFile jarFile =

conn.getJarFile();

Enumeration

entries = jarFile.entries();

while (entries.hasMoreElements()) {

JarEntry jarEntry =

entries.nextElement();

String name =

jarEntry.getName();

if (name.contains(".class") &&

name.replaceAll("/", ".").startsWith(packagePath)) {

String className =

name.substring(0,

name.lastIndexOf(".")).replace("/", ".");

try {

Class clazz =

Class.forName(className);

res.add(clazz);

} catch (ClassNotFoundException

e) {

e.printStackTrace();

}

}

}

}

return res;

}

public static void main(String[]

args) {

Set classes =

Utils.getClasses("com.ioc");

classes.addAll(Utils.getClasses("net.sf"));

for (Class clazz : classes) {

System.out.println(clazz.getName());

}

}

}

这里扫描的src结构是

扫描的Jar文件是 cglib.jar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值