AbstractBaseJavaLocalInspectionTool 是 IntelliJ IDEA 插件开发中用于实现 Java 代码本地检查的核心基类,其功能特性及实现逻辑如下:
一、核心功能
- 代码静态分析
继承该类的插件可对 Java 文件进行语法树解析,识别潜在问题(如代码规范、安全隐患等),并在编辑器中实时提示用户。 - 自定义检查规则
开发者需重写buildVisitor
方法,通过访问 PSI(Program Structure Interface)元素实现特定检查逻辑。例如检测未使用的变量或不符合命名规范的代码段。 - 多级问题分类
支持通过ProblemHighlightType
定义问题的严重程度(如错误、警告、弱警告),并通过registerProblem
方法在代码位置标注提示信息。
代码实现
- 代码分析逻辑
java
public class SpecificationInspectionTool extends AbstractBaseJavaLocalInspectionTool {
@Override
public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitField(@NotNull PsiField field) {
super.visitField(field);
PsiClass containingClass = field.getContainingClass();
if ( isChangeFile(field.getContainingFile()) ) {
PsiAnnotation[] annotations = field.getAnnotations();
Boolean haveDongBootAnnotation = Boolean.FALSE;
for (PsiAnnotation annotation : annotations) {
haveDongBootAnnotation = Boolean.TRUE;
break;
}
if (!haveDongBootAnnotation) {
holder.registerProblem(
field.getNameIdentifier(),
"字段上没有xxxxx",
ProblemHighlightType.WARNING
);
}
}
}
private Boolean isChangeFile(PsiFile containingFile) {
ChangeListManager changeListManager = ChangeListManager.getInstance(containingFile.getProject());
Collection<VirtualFile> changedFiles = changeListManager.getAffectedFiles();
boolean retBol = changedFiles.stream().anyMatch(file -> {
return Objects.equals(file.getCanonicalPath(), containingFile.getVirtualFile().getCanonicalPath());
});
return retBol;
}
};
}
}
- 工具生效配置
xml
<extensions defaultExtensionNs="com.intellij">
<localInspection
language="JAVA"
displayName="文档规范检查"
groupPath="Java"
groupBundle="messages.InspectionsBundle"
groupKey="group.names.probable.bugs"
enabledByDefault="true"
level="WARNING"
implementationClass="xx.xx.SpecificationInspectionTool"/>
</extensions>