如何通过IntelliJ插件API获取虚拟文件及项目的错误信息?
获取IntelliJ Problems工具窗口内容及错误信息API
Problems工具窗口展示的是IDE对代码的诊断结果(错误、警告、检查提示等),无需直接抓取UI元素,通过IntelliJ Platform提供的API就能直接获取这些数据,以下是具体实现方式:
一、获取当前文件的错误信息
当前文件的诊断信息可通过编辑器标记模型或Inspection相关API获取:
- 方式1:读取编辑器已有的高亮标记
编辑器的MarkupModel存储了所有代码高亮(包括错误标记),可筛选出错误类型标记并获取其描述:// 获取当前项目与编辑器实例 Project project = MyPlugin.getProject(); Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor == null) return; EditorMarkupModel markupModel = editor.getMarkupModel(); Collection<RangeHighlighter> highlighters = markupModel.getAllHighlighters(); EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); Color errorStripeColor = scheme.getColor(EditorColors.ERROR_STRIPE_COLOR); for (RangeHighlighter highlighter : highlighters) { TextAttributes attrs = highlighter.getTextAttributes(); // 判断是否为错误标记 if (attrs.getErrorStripeColor() != null && attrs.getErrorStripeColor().equals(errorStripeColor)) { String problemDesc = highlighter.getTooltip(); // 处理错误内容,比如打印或存储 System.out.println(problemDesc); } } - 方式2:主动触发检查获取结果
若需实时获取最新检查结果,可通过InspectionManager对当前文件运行指定检查:PsiFile psiFile = ...; // 获取当前文件的Psi实例 InspectionManager inspectionManager = InspectionManager.getInstance(project); GlobalInspectionContext context = inspectionManager.createNewGlobalContext(); // 指定要运行的检查(比如通用代码检查) AbstractBaseJavaLocalInspectionTool inspection = new GeneralCodeStyleInspection(); List<ProblemDescriptor> problems = new ArrayList<>(); context.runInspectionOnFile(psiFile, inspection, problems::addAll); for (ProblemDescriptor problem : problems) { String desc = problem.getDescriptionTemplate(); PsiElement targetElement = problem.getPsiElement(); // 处理检查结果 }
二、获取整个项目的错误信息
使用ProjectProblemManager可直接获取项目范围内所有已诊断的问题:
Project project = ...; List<ProblemDescriptor> allProjectProblems = ProjectProblemManager.getInstance(project).getAllProblems(); for (ProblemDescriptor problem : allProjectProblems) { String problemDesc = problem.getDescriptionTemplate(); PsiElement element = problem.getPsiElement(); String filePath = element.getContainingFile().getVirtualFile().getPath(); // 处理项目级错误,比如按文件分类统计 }
关键API说明
ProblemDescriptor:单个代码问题的核心载体,包含问题描述、关联Psi元素、严重程度等信息EditorMarkupModel:编辑器的标记模型,存储所有代码高亮、错误标记等UI元数据ProjectProblemManager:管理项目范围内的所有诊断问题,提供批量获取接口InspectionManager:用于触发代码检查,获取实时诊断结果
内容的提问来源于stack exchange,提问作者Sheng Chen
相关产品推荐
相关产品推荐

