获得指定包名下的所有类全路径:
/**
* 获得对应包下的类名称(自动遍历子包)
* <功能详细描述>
* @param packageName
* @return
*/
public static List<String> getClassName(String packageName)
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String packagePath = packageName.replace(".", "/");
//加载包下的所有资源
URL url = loader.getResource(packagePath);
List<String> fileNames = null;
if (url != null)
{
String type = url.getProtocol();
if (type.equals("file"))
{
fileNames = getClassName(url.getPath(), null);
}
}
return fileNames;
}
/**
* 根据资源路径返回 class 路径
* <功能详细描述>
* @param filePath
* @param className
* @return
*/
private static List<String> getClassName(String filePath, List<String> className)
{
List<String> myClassName = new ArrayList<String>();
File file = new File(filePath);
File[] childFiles = file.listFiles();
for (File childFile : childFiles)
{
if (childFile.isDirectory())
{
myClassName.addAll(getClassName(childFile.getPath(), myClassName));
}
else
{
String childFilePath = childFile.getPath();
childFilePath =
childFilePath.substring(childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf("."));
childFilePath = childFilePath.replace("\\", ".");
myClassName.add(childFilePath);
}
}
return myClassName;
}
/**
* 获得对应包下的类名称(自动遍历子包)
* <功能详细描述>
* @param packageName
* @return
*/
public static List<String> getClassName(String packageName)
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String packagePath = packageName.replace(".", "/");
//加载包下的所有资源
URL url = loader.getResource(packagePath);
List<String> fileNames = null;
if (url != null)
{
String type = url.getProtocol();
if (type.equals("file"))
{
fileNames = getClassName(url.getPath(), null);
}
}
return fileNames;
}
/**
* 根据资源路径返回 class 路径
* <功能详细描述>
* @param filePath
* @param className
* @return
*/
private static List<String> getClassName(String filePath, List<String> className)
{
List<String> myClassName = new ArrayList<String>();
File file = new File(filePath);
File[] childFiles = file.listFiles();
for (File childFile : childFiles)
{
if (childFile.isDirectory())
{
myClassName.addAll(getClassName(childFile.getPath(), myClassName));
}
else
{
String childFilePath = childFile.getPath();
childFilePath =
childFilePath.substring(childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf("."));
childFilePath = childFilePath.replace("\\", ".");
myClassName.add(childFilePath);
}
}
return myClassName;
}