简体   繁体   English

如何为导入语句创建自定义 IntelliJ 警告/错误?

[英]How do I create a custom IntelliJ warning/error for import statements?

I want to add a custom warning/error to IntelliJ that triggers if my Java project contains imports to a certain package.我想向 IntelliJ 添加一个自定义警告/错误,如果我的 Java 项目包含对某个 package 的导入,则会触发该警告/错误。

I have looked into Search Templates/Replace Templates , but whenever I try to type code with an "import", it gives me an "Unexpected Token" error and refuses to be created.我已经研究了Search Templates/Replace Templates ,但是每当我尝试使用“导入”键入代码时,它都会给我一个“意外令牌”错误并拒绝创建。

This is fine:这可以:

“class MyCLass {}”不会导致错误,并且可以选择确定按钮

This is not:这不是:

“import System.out; class MyClass {}”导致弹出“Unexpected token”,确定按钮灰显

I also can't find examples of search templates that match on import statements.我也找不到与导入语句匹配的搜索模板示例。 The closest thing I can find is an example in the above link where a "use static imports" checkbox is available that will make the replacement's output contain a static import.我能找到的最接近的是上面链接中的一个示例,其中“使用 static 导入”复选框可用,这将使替换的 output 包含 ZA81259CEF8E959C624DF1D456E5D3297。

Do search templates just not support matching on import statements for some reason, and if so why?搜索模板是否出于某种原因不支持匹配导入语句,如果是,为什么? Is there another way to do what I want to do?还有另一种方法可以做我想做的事吗?

Thanks in advance.提前致谢。

My IntelliJ version is 2022.2我的 IntelliJ 版本是 2022.2

Structural search for imports/packages is not supported yet - https://youtrack.jetbrains.com/issue/IDEA-285199 .尚不支持导入/包的结构搜索 - https://youtrack.jetbrains.com/issue/IDEA-285199

As a workaround you can try using the following template:作为一种解决方法,您可以尝试使用以下模板:

<searchConfiguration name="Unnamed" text="$Type$" recursive="true" type="JAVA" pattern_context="default" search_injected="false">
  <constraint name="__context__" within="" contains="" />
  <constraint name="Type" regexp="javafx\..*" within="" contains="" />
</searchConfiguration>

Use the Import Template from Clipboard action under the tool button in the Structural Search dialog:使用结构搜索对话框中工具按钮下的Import Template from Clipboard操作:

在此处输入图像描述

I think "illegal package dependencies" inspection is what you are looking for.我认为您正在寻找“非法 package 依赖项”检查。 It can be found under "Settings/Editor/Inspections/JVM languages/Illegal package dependencies".它可以在“设置/编辑器/检查/JVM 语言/非法 package 依赖项”下找到。 You can create a custom scope for all the dependencies that you don't want in your project and apply them to the predefined "All" scope.您可以为项目中不需要的所有依赖项创建自定义 scope,并将它们应用到预定义的“全部”scope。 Example例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM