先点击收藏和点赞,切勿白嫖,感谢
前言
统计某包下边所有mapper接口下的所有方法数量
代码
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Enumeration;
/**
* @author baicaizhi
*/
public class Test {
public static void main(String[] args) {
String packageName = "com.baicaizhi"; // 修改为你的包名
int methodCount = countMethodsInMappers(packageName);
System.out.println("所有 Mapper 类中的方法总数: " + methodCount);
}
/**
* 递归遍历
* @param packageName 项目包名称
* @return
*/
private static int countMethodsInMappers(String packageName) {
int totalMethods = 0;
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
File dir = new File(resources.nextElement().getFile());
if (dir.exists()) {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
totalMethods += countMethodsInMappers(packageName + "." + file.getName());
} else if (file.getName().endsWith("Mapper.class")) {
String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
Class<?> clazz = Class.forName(className);
if (clazz.getSimpleName().endsWith("Mapper")) {
Method[] methods = clazz.getDeclaredMethods();
System.out.println(clazz.getSimpleName()+":"+methods);
totalMethods += methods.length;
}
}
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return totalMethods;
}
}