package edu.nf.beans.util;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;/**
* Created by Administrator on 2017/12/12.*/
public classScanUtil {//定义一个set来保存完整类名
private static Set classNames = new HashSet();public static Setscan(String packageName) {if(packageName==null){//抛异常
throw new RuntimeException("The path can not be null.");
}//传入的包名格式为 edu.nf 进行转换
String packagePath = packageName.replace(".","\\");//根据当前线程当前执行类获取url
ClassLoader loader =Thread.currentThread().getContextClassLoader();try{//枚举获得一个路径
Enumeration urls =loader.getResources(packagePath);while (urls.hasMoreElements()){//如果不为空
URL url = urls.nextElement();//获取路径
System.out.println(url+"111");if("file".equals(url.getProtocol())){//如果是文件
String path = URLDecoder.decode(url.getPath(),"utf-8");//处理中文乱码
scanFromDir(path,packageName);//进行类扫描,保存Set集合
}if("jar".equals(url.getProtocol())){//如果是jar
JarURLConnection connection =(JarURLConnection)url.openConnection();
String pathjar= URLDecoder.decode(String.valueOf(connection),"utf-8");
scanFromDir(pathjar,packageName);
}
}
}catch(IOException e) {throw new RuntimeException("Resolve path error.", e);
}returnclassNames;
}/**
* 从项目文件获取某包下所有类
* @param filePath 文件目录
* @param packageName 包名*/
private static voidscanFromDir(String filePath,String packageName){
File[] files= newFile(filePath).listFiles();
packageName= packageName + ".";for (File childFile:files){ //遍历文件
if(childFile.isDirectory()){//还是文件夹就继续递归
scanFromDir(childFile.getPath(),packageName+childFile.getName());
}else{
String fileName= childFile.getName();//文件名
if(fileName.endsWith(".class")){//判断文件名是否是.class结尾
if(packageName.charAt(0)=='.'){//判断开头是否有'.',有的话截取
packageName = packageName.substring(1,packageName.length());
}//拼接字符串,得到完整类名 如:edu.nf.beans.util.ScanUtil
String className = packageName+fileName.replace(".class","");
classNames.add(className);
}
}
}
}public static voidmain(String[] args) {
Set classNames=scan("edu.nf");for(String path:classNames){
System.out.println(path);
}
}
}