且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Checkstyle规则限制根包之间的交互(使用ImportControl?)

更新时间:2021-08-10 10:20:44

不幸的是,你想要的东西很难用ImportControl开箱即用。
这就是原因:

Unfortunately, what you want is very hard to do using the ImportControl check out of the box.
Here's why:

你已经找到了为什么你的选择1不能工作:只能有一个根包。

You already found out why your option 1 cannot work: There can only be one root package.

选项2是可能的,但很费力。让我深入一点。我使用了以下两个导入控制文件,它们禁止从视图视图中使用模型 / code>来自 models

Option 2 is possible, but laborious. Let me go into some depth. I used the following two import control files, which disallow using models from views and views from models:

<!DOCTYPE import-control PUBLIC "-//Puppy Crawl//DTD Import Control 1.1//EN"
    "http://www.puppycrawl.com/dtds/import_control_1_1.dtd">
<import-control pkg="views">
    <allow pkg="views" />
    <disallow pkg="models" />
</import-control>



<!DOCTYPE import-control PUBLIC "-//Puppy Crawl//DTD Import Control 1.1//EN"
    "http://www.puppycrawl.com/dtds/import_control_1_1.dtd">
<import-control pkg="models">
    <allow pkg="models" />
    <disallow pkg="views" />
</import-control>

在我的测试设置中,这基本上有效,但有一个缺点:每个班级都会收到一个Checkstyle警告导入控制文件不处理此包。这是因为ImportControl检查要求所有包都驻留在公共根目录下(通过查看Checkstyle 5.6源代码进行验证)。因此,在 models 包中,您将从为 views 包配置的检查实例收到警告,反之亦然。

还有一个问题,即ImportControl检查仅适用于import语句,但没有找到代码中直接使用的完全限定引用。

In my test setup, this basically worked, but there is a drawback: Every class gets a Checkstyle warning that the Import control file does not handle this package. This is because the ImportControl check expects all packages to reside under a common root (verified by looking at the Checkstyle 5.6 sources). So in the models package, you get the warning from the check instance configured for the views package, and vice versa.
There is also the added problem that the ImportControl check only works on the import statements, but does not find fully qualified references used directly in the code.

那么,你能做什么?


  • 更改你的应用程序,以便拥有一个共同的根目录。这是***实践,通常也是一个好主意。

  • 将自定义检查实现为 ImportControlCheck ,它添加了启用/禁用导入的选项控制文件不处理此包消息,否则请使用您的选项2。

  • 如果您使用的是Eclipse,还有第三种解决方案。您可以使用Checkstyle Eclipse插件提供的高级配置对话框,以将ImportControl实例限制为各自的文件。这也将消除导入控制文件不处理此包消息。

  • Change your app so that you have a common root. This is best practice and generally a good idea.
  • Implement a custom check as a subclass of ImportControlCheck which adds an option for enabling/disabling the "Import control file does not handle this package" message, and otherwise go with your option 2.
  • If you are using Eclipse, there is also a third solution. You could use the advanced configuration dialog that the Checkstyle Eclipse plugin provides in order to restrict the ImportControl instances to their respective files. This would also eliminate the "Import control file does not handle this package" messages.