测试demo; git仓库 : https://github.com/alwaysInRoad/test-forEach-package.git
csdn下载地址:https://download.csdn.net/download/weixin_40841731/10707911
demo为普通项目,引入普通java project就可以了
1、说明:
此类为本人开发的工具类,具体应用在什么地方呢。本人在实际项目中,权限管理这一块有所应用,应该是权限这一块有所需求而开发的。
应用场景说明:权限资源自动化生产时,用户点击界面的一键生成资源时,接口中就会遍历指定controller包下所有类,返回所有类名。在通过反射获取每一个url地址,与地址上的解释,生产一一对应的资源。
例如: 所用主要框架: spring boot、swagger2
代码段:
@ApiOperation("根据id删除用户")
@DeleteMapping(value = "/byId/{id}")
public RetEntity<Users> deleteUser(@PathVariable("id") String id) throws CommonException {
RetEntity<Users> retEntity = usersService.deleteUser(id);
return retEntity;
}
生成的资源格式:“根据id删除用户”,“/users/byId/{id}”
2、类 ClassUtils.java
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ClassUtils {
// public static void main(String[] args) {
// String packageName = ""; //填入完整包名,如com.org.String
// Set<String> classNames = getClassName(packageName, false);
// if (classNames != null) {
// for (String className : classNames) {
// System.out.println(className);
// }
// }
// }
/**
* 获取某包下所有类
*
* @param packageName 包名
* @param isRecursion 是否遍历子包
* @return 类的完整名称
*/
public static Set<String> getClassName(String packageName, boolean isRecursion) {
Set<String> classNames = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String packagePath = packageName.replace(".", "/");
URL url = loader.getResource(packagePath);
if (url != null) {
String protocol = url.getProtocol();
if (protocol.equals("file")) {
classNames = getClassNameFromDir(url.getPath(), packageName, isRecursion);
} else if (protocol.equals("jar")) {
JarFile jarFile = null;
try {
jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
} catch (Exception e) {
e.printStackTrace();
}
if (jarFile != null) {
getClassNameFromJar(jarFile.entries(), packageName, isRecursion);
}
}
} else {
/*从所有的jar包中查找包名*/
classNames = getClassNameFromJars(((URLClassLoader) loader).getURLs(), packageName, isRecursion);
}
return classNames;
}
/**
* 从项目文件获取某包下�?有类
*
* @param filePath 文件路径
* @param className 类名集合
* @param isRecursion 是否遍历子包
* @return 类的完整名称
*/
private static Set<String> getClassNameFromDir(String filePath, String packageName, boolean isRecursion) {
Set<String> className = new HashSet<String>();
File file = new File(filePath);
File[] files = file.listFiles();
for (File childFile : files) {
//�?查一个对象是否是文件�?
if (childFile.isDirectory()) {
if (isRecursion) {
className.addAll(getClassNameFromDir(childFile.getPath(), packageName + "." + childFile.getName(), isRecursion));
}
} else {
String fileName = childFile.getName();
//endsWith() 方法用于测试字符串是否以指定的后�?结束�? !fileName.contains("$") 文件名中不包�? '$'
if (fileName.endsWith(".class") && !fileName.contains("$")) {
className.add(packageName + "." + fileName.replace(".class", ""));
}
}
}
return className;
}
/**
* @param jarEntries
* @param packageName
* @param isRecursion
* @return
*/
private static Set<String> getClassNameFromJar(Enumeration<JarEntry> jarEntries, String packageName, boolean isRecursion) {
Set<String> classNames = new HashSet<String>();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
if (!jarEntry.isDirectory()) {
/*
* 这里是为了方便,先把"/" 转成 "." 再判�? ".class" 的做法可能会有bug
* (FIXME: 先把"/" 转成 "." 再判�? ".class" 的做法可能会有bug)
*/
String entryName = jarEntry.getName().replace("/", ".");
if (entryName.endsWith(".class") && !entryName.contains("$") && entryName.startsWith(packageName)) {
entryName = entryName.replace(".class", "");
if (isRecursion) {
classNames.add(entryName);
} else if (!entryName.replace(packageName + ".", "").contains(".")) {
classNames.add(entryName);
}
}
}
}
return classNames;
}
/**
* 从所有jar中搜索该包,并获取该包下�?有类
*
* @param urls URL集合
* @param packageName 包路�?
* @param isRecursion 是否遍历子包
* @return 类的完整名称
*/
private static Set<String> getClassNameFromJars(URL[] urls, String packageName, boolean isRecursion) {
Set<String> classNames = new HashSet<String>();
for (int i = 0; i < urls.length; i++) {
String classPath = urls[i].getPath();
//不必搜索classes文件�?
if (classPath.endsWith("classes/")) {
continue;
}
JarFile jarFile = null;
try {
jarFile = new JarFile(classPath.substring(classPath.indexOf("/")));
} catch (IOException e) {
e.printStackTrace();
}
if (jarFile != null) {
classNames.addAll(getClassNameFromJar(jarFile.entries(), packageName, isRecursion));
}
}
return classNames;
}
}
结语:本人所有文章都立志写的简单易懂,戳中问题点。 当然了,简单的同时可能忽略了很多细节与详细,如有不足的地方,还请谅解并指出。 如对文章或实现技术上有问题,可联系我:qq: 1226500260 邮箱:[email protected]