1、添加依赖
<!-- javaParser -->
<dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>3.25.8</version>
</dependency>
<!-- hutool -->
<dependency>
<groupId>org.dromara.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>6.0.0-M10</version>
</dependency>
2、代码分析
代码整体结构分析:
AnalyzerUnusedMethodUtil
类是主类,包含了main
方法作为程序的入口点。- 类中定义了三个静态常量,分别为
EXCLUDE_DIRECTORY
、CALLED_METHOD_MAP
和ALL_METHOD_MAP
,用于存储排除目录、调用方法和所有方法的信息。 - 私有化构造器用于防止实例化该类。
main
方法首先创建一个StopWatch
对象,用于计时。- 然后指定要扫描的目录路径,并通过调用
loopFiles
方法获取该目录下的所有Java文件的列表。 - 遍历文件列表,使用JavaParser库解析每个文件,并通过自定义的
MethodDeclarationVisitor
访问器,获取所有方法的声明,并将其存储在ALL_METHOD_MAP
中。 - 接下来,再次遍历文件列表,通过自定义的
MethodReferenceVisitor
访问器,检查每个方法是否被调用,并将调用的方法存储在CALLED_METHOD_MAP
中。 - 完成遍历后,停止计时,并输出总耗时和未使用的方法列表。
loopFiles
方法是一个递归方法,用于获取指定目录下的所有Java文件。MethodReferenceVisitor
和MethodDeclarationVisitor
是两个内部类,分别继承自VoidVisitorAdapter
类,用于访问语法树中的方法节点,实现对方法声明和方法调用的处理逻辑。
总体来说,该代码通过使用JavaParser库对Java代码进行解析,实现了对指定目录下的方法进行分析,判断是否未被使用。它采用了访问者模式,将方法的声明和方法的调用分别处理,最终输出未使用的方法列表。
3、未使用方法完整代码
以下代码是一个用于分析未使用方法的工具类AnalyzerUnusedMethodUtil。它通过使用JavaParser库解析Java代码文件,遍历项目目录下的所有Java文件,检查指定目录中的service、mapper、manager等几个目录下的方法是否未被使用。它实现了两个自定义的Visitor类,分别用于获取所有方法的声明和方法的调用。通过比较方法名和类名,以及检查方法的可见性范围和成员变量申明,该工具能够识别出未被调用的方法。最终,它会输出未使用的方法列表。
import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseProblemException;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import com.google.common.collect.Lists;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.date.StopWatch;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.text.StrPool;
import org.dromara.hutool.core.util.ObjUtil;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* 分析未使用方法,主要分析service、mapper、manager这几个目录下方法是否未被使用
*
* @author 管理员
* @since 2024/3/8
*/
public final class AnalyzerUnusedMethodUtil {
/**
* 排除目录
*/
private static final List < String > EXCLUDE_DIRECTORY = Lists.newArrayList("advice", "config", "init", "listener",
"controller", "impl", "task", "aspect", "pojo");
/**
* 调用方法
*/
private static final Map < String, String > CALLED_METHOD_MAP = new ConcurrentHashMap <>();
/**
* 所有方法
*/
private static final Map < String, List < String > > ALL_METHOD_MAP = new ConcurrentHashMap <>();
/**
* 私有化构造器
*/
private AnalyzerUnusedMethodUtil() {
}
/**
* 分析未使用方法
*
* @param args 启动参数
*/
@SuppressWarnings("checkstyle:UncommentedMain")
public static void main(String[] args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
String scanPath = "D:\\workspace\\shrimp-paste\\src\\main\\java\\com\\frontier\\shrimp";
List < File > fileList = loopFiles(new File(scanPath));
fileList.forEach(file -> {
try {
JavaParser javaParser = new JavaParser();
ParseResult < CompilationUnit > parseResult = javaParser.parse(file);
if (parseResult.isSuccessful()) {
CompilationUnit compilationUnit = parseResult.getResult()
.orElseThrow(() -> new IllegalStateException("AllMethod failed to parse file: " + file));
String nameAsString = compilationUnit.getType(0).getNameAsString();
// 创建一个Visitor来访问语法树中的方法节点
MethodDeclarationVisitor methodDeclarationVisitor = new MethodDeclarationVisitor(nameAsString);
// 使用Visitor访问语法树
methodDeclarationVisitor.visit(compilationUnit, null);
}
else {
System.out.println("AllMethod Parse file: " + file);
}
}
catch (ParseProblemException | IOException exception) {
exception.printStackTrace();
}
});
fileList = FileUtil.loopFiles(new File(scanPath));
List < File > finalFileList = fileList;
ALL_METHOD_MAP.forEach((className, methodList) -> {
methodList.forEach(method -> {
for (File file : finalFileList) {
if (ObjUtil.isNotNull(CALLED_METHOD_MAP.get(className + method))) {
System.out.println(className + StrPool.DOT + method + " 方法已存在引用,终止文件检查");
break;
}
try {
JavaParser javaParser = new JavaParser();
ParseResult < CompilationUnit > parseResult = javaParser.parse(file);
if (parseResult.isSuccessful()) {
CompilationUnit compilationUnit = parseResult.getResult()
.orElseThrow(() -> new IllegalStateException("Failed to parse file: " + file));
// 创建一个Visitor来访问语法树中的方法节点
MethodReferenceVisitor methodReferenceVisitor = new MethodReferenceVisitor(className,
method, compilationUnit);
// 使用Visitor访问语法树
methodReferenceVisitor.visit(compilationUnit, null);
}
else {
System.out.println("Parse file: " + file);
}
}
catch (ParseProblemException | IOException exception) {
exception.printStackTrace();
}
}
});
});
stopWatch.stop();
System.out.println();
System.out.println("获取所有任务的总花费时间(秒):" + stopWatch.getTotalTimeSeconds());
System.out.println("Unused methods:");
ALL_METHOD_MAP.forEach((className, methodList) -> {
methodList.forEach(method -> {
String calledMethodName = CALLED_METHOD_MAP.get(className + method);
if (CharSequenceUtil.isBlank(calledMethodName)) {
System.out.println(className + StrPool.DOT + method);
}
});
});
}
/**
* 递归获取项目目录下的所有Java文件
*
* @author 管理员
* @date 2024/2/19
* @param directory 目录
* @return 所有Java文件
*/
private static List < File > loopFiles(File directory) {
List < File > javaFiles = new ArrayList <>();
File[] files = directory.listFiles();
// 目录下无对应文件直接返回
if (files == null) {
return javaFiles;
}
// 遍历文件或目录
for (File file : files) {
String fileName = file.getName();
// 如果是目录并且非排除目录,递归获取对应文件
if (file.isDirectory() && !CollUtil.contains(EXCLUDE_DIRECTORY, fileName)) {
javaFiles.addAll(loopFiles(file));
}
else if (file.isFile() && CharSequenceUtil.endWith(fileName, "java")) {
// 添加对应java文件
javaFiles.add(file);
}
}
return javaFiles;
}
/**
* 自定义Visitor,用于获取所有方法申明
*
* @author 管理员
* @date 2024/3/11
*/
private static class MethodReferenceVisitor extends VoidVisitorAdapter < Void > {
/**
* 程序代码编译单元
*/
private final CompilationUnit compilationUnit;
/**
* 类名
*/
private final String className;
/**
* 方法名
*/
private final String methodName;
/**
* 构造方法
*
* @param className 类名
* @param methodName 方法名
* @param compilationUnit 程序代码编译单元
*/
MethodReferenceVisitor(String className, String methodName, CompilationUnit compilationUnit) {
this.className = className;
this.methodName = methodName;
this.compilationUnit = compilationUnit;
}
@Override
public void visit(MethodCallExpr method, Void arg) {
super.visit(method, arg);
// 获取调用方法名称
String calledMethodName = method.getNameAsString();
// 检查的方法名称与调用方法名称是否一致
if (!CharSequenceUtil.equals(methodName, calledMethodName)) {
return;
}
// 检查的方法名称与调用方法名称一致,方法名称一致不代表就是方法被调用
// 还需要判断类名是否一致,项目中方法名称相同的往往比较多
// 获取该方法的可见性范围
Optional < Expression > scope = method.getScope();
// 方法成员变量
String methodVariablesName;
// NameExpr是一个表示名称表达式的类,只表示一个简单的名称,如变量名,方法名等
if (scope.isPresent() && scope.get() instanceof NameExpr) {
// 获取当前方法的变量,如:xxxMapper.updateUser,获取的则是xxxMapper
NameExpr nameExpr = (NameExpr) scope.get();
methodVariablesName = nameExpr.getNameAsString();
}
else {
methodVariablesName = null;
}
// 如果是静态方法(工具类等),方法成员变量(methodVariablesName)是和className是一致的
if (CharSequenceUtil.equals(className, methodVariablesName)) {
CALLED_METHOD_MAP.put(className + calledMethodName, calledMethodName);
return;
}
// 私有方法是否被调用检查
String currentClassName = compilationUnit.getType(0).getNameAsString();
// 当前类和检查的类为同一个类时,则表示是当前类的私有方法被调用
if (CharSequenceUtil.equals(className, currentClassName)) {
CALLED_METHOD_MAP.put(className + calledMethodName, calledMethodName);
return;
}
// 查找当前类中所有的成员变量申明,找出该类中申明和methodVariablesName相同的
FieldDeclaration fieldDeclaration = compilationUnit.findAll(FieldDeclaration.class).stream()
.filter(declaration -> {
VariableDeclarator variable = declaration.getVariable(0);
String variableName = variable.getNameAsString();
return CharSequenceUtil.equals(methodVariablesName, variableName);
}).findFirst().orElse(null);
// 如获取到成员变量申明,下一步获取变量类名
if (null != fieldDeclaration) {
// 如:private XxxMapper xxxMapper,获取的则是XxxMapper
String typeName = fieldDeclaration.getVariable(0).getTypeAsString();
// 对比获取的类名和传入的类名是否为同一个,如是则表示方法被调用
if (CharSequenceUtil.equals(typeName, className)) {
CALLED_METHOD_MAP.put(className + calledMethodName, calledMethodName);
}
}
}
}
/**
* 自定义Visitor,用于获取所有方法申明
*
* @author 管理员
* @date 2024/3/11
*/
private static class MethodDeclarationVisitor extends VoidVisitorAdapter < Void > {
/**
* 类名
*/
private final String className;
/**
* 构造方法
*
* @param className 类名
*/
MethodDeclarationVisitor(String className) {
this.className = className;
}
@Override
public void visit(MethodDeclaration method, Void arg) {
super.visit(method, arg);
// 获取方法名称
String methodName = method.getNameAsString();
List < String > methodList = ALL_METHOD_MAP.get(className);
// 当前类方法集合为空时,为该类创建一个方法集合并加入map中
if (CollUtil.isEmpty(methodList)) {
ALL_METHOD_MAP.put(className, Lists.newArrayList(methodName));
}
else {
methodList.add(methodName);
}
}
}
}
如需要了解JavaParser库简单使用,可参照文章:优化代码质量的利器、高效清理Java项目中的垃圾类、精确定位无用类,开发者必备利器、加速代码开发与维护、暴打IDEA识别无用类