【问题标题】:IntelliJ IDEA @SuppressWarnings for inspection with name of toolIntelliJ IDEA @SuppressWarnings 用于检查工具名称
【发布时间】:2015-09-02 21:17:25
【问题描述】:

我知道我可以抑制来自 IntelliJ IDEA 检查的警告:

@SuppressWarnings("CollectionDeclaredAsConcreteClass")
public PropertiesExpander(Properties properties) {
    this.properties.putAll(properties);
}

对于来自外部的人,可能不清楚哪个工具需要这种抑制。

PMD 为此使用前缀:

@SuppressWarnings("PMD.UnusedLocalVariable")

FindBugs 使用专用注解:

@SuppressFBWarnings("NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR")

有什么方法可以明确表明这种抑制只是针对 IntelliJ IDEA 的?

【问题讨论】:

    标签: java intellij-idea suppress-warnings code-inspection


    【解决方案1】:

    我找到了一种使用@SuppressWarnings 实现这一目标的方法:

    @SuppressWarnings("idea: CollectionDeclaredAsConcreteClass")
    public PropertiesExpander(Properties properties) {
        this.properties.putAll(properties);
    }
    

    注意idea:后面一定要有空格,否则不起作用。

    【讨论】:

    • 说实话我更喜欢你的解决方案。 IntelliJ 中的注释是灰色的,它们不会像 @SuppressWarnings 那样污染代码。
    【解决方案2】:

    一种抑制方法参数的方法是使用 javadoc 标记:

    /**
     * @noinspection CollectionDeclaredAsConcreteClass
     */
    public PropertiesExpander(Properties properties) {
        this.properties.putAll(properties);
    }
    

    这个 javadoc 标签是非常特定于 IntelliJ 的,所以其他工具应该不会有任何问题。你可以很容易地识别它,只需识别它的原样或添加一些评论:

    /**
     * @noinspection IntelliJ CollectionDeclaredAsConcreteClass
     */
    public PropertiesExpander(Properties properties) {
        this.properties.putAll(properties);
    }
    

    当然你可以把它缩短得更多:

    /** @noinspection CollectionDeclaredAsConcreteClass */
    public PropertiesExpander(Properties properties) {
        this.properties.putAll(properties);
    }
    

    一般方法

    可以使用特殊的 cmets 而不是 @SuppressWarnings 注释逐个抑制某些警告。

    这是一个带有大量警告的示例:

    如果您在notUsedLocalVariable 上按Alt+Enter,则可以在上下文菜单上选择Suppress for statement with comment(在选择Remove variable ... 时向右移动后)。

    在某些变量/字段/方法上,选择的抑制只是Suppress for statement

    如果您查看右侧字段,现在大多数(不是全部)警告已被抑制:

    如您所见,同一注释行可以有多个抑制。

    这似乎有点乏味,但我认为这是你能做的最好的。

    【讨论】:

    • 谢谢,我知道添加 cmets 而不是 @SuppressWarnings 的可能性,但如果警告来自方法参数,它对我不起作用。也许我不够精确,但我是在具体询问我给出的示例中的案例。
    • @MichalKordas 我编辑了我的答案并提出了另一种抑制这种情况的方法。它确实适用于您的情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    相关资源
    最近更新 更多