如何为 @Nullable 注释启用 Android lint 检查?

How to enable Android lint check for the @Nullable annotation?

我注意到 Android Studio 将验证 @Nullable 没有在代码中被忽略:

例如

@Nullable MyObject getMyObject();
...

MyObject o = getMyObject();
o.method();

^ Method invocation 'method' may produce 'java.lang.NullPointerException'

这是由 NullableProblems IntelliJ 警告强制执行的。

我想在构建时通过 lint 规则从 gradle 强制执行此规则。有没有人碰巧知道是否可以通过 gradle 启用类似的功能?

如果有问题的检查是 lint,将有一种方法可以在 build.gradle 中配置 lintOptions 以强制构建失败,如 [=22 的答案所示=]

但是,您所说的检查是由 IDE 本身在 Android Studio 中提供的。根据 IntelliJ 提供的此静态代码分析的 this canonical answer from a IntelliJ developer Here is a link to the documentation,目前无法停止这些检查的构建。在文档中解释的分析中,具体名称是"Constant conditions & exceptions":

This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations. Variables, method parameters and return values marked as @Nullable or @NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report possible NullPointerException errors.

我认为您能做的最好的事情就是更改其严重性,使其显示为警告(IDE 中的红色下划线)。这样做,转到 Preferences / Inspections / Probable Bugs 并将 "Constant conditions & exceptions" 的严重性更改为 warning:

如果您忽略警告,您的项目仍会生成,但它看起来不会很好:

您必须对其进行设置,以便您的团队共享相同的 Android Studio 代码检查设置。您可以使用 settings repository.

另请注意,您还可以启用“提交更改/执行代码分析”复选框,这将在团队提交之前强制执行代码分析。

当你点击commit时,它首先进行分析,发现你一直在说的警告:

另请注意,如果 NPE 在项目中成为问题,强制 团队使用这样的检查可能不是最佳选择。相反,您可以尝试一些选项,例如公开讨论返回 null 产生的问题和可能的解决方案。 Google Guava wiki 中的 This excellent article on avoiding null 是一个很好的起点。

如果您希望lint 在源代码中的某些规则被破坏时抛出错误,您绝对可以将项目配置为源代码编译停止的方式。我本可以写出整个过程,但是这个 link 或多或少总结了整个过程

还要经过Androidlinkdoc

注意:Android Studio 菜单中的 Analyze 选项主要使用 Lint 和内置 Intellij Idea Code inspection