【问题标题】:How to suppress FindBugs warnings for fields or local variables?如何抑制字段或局部变量的 FindBugs 警告?
【发布时间】:2013-01-08 07:21:53
【问题描述】:

我想禁止针对特定字段或局部变量的 FindBugs 警告。 FindBugs 记录了Target 可以是TypeFieldMethodParameterConstructorPackagePackage 注释[1]。 但是注释字段对我不起作用,只有当我注释方法时,警告才会被抑制。

注释整个方法对我来说似乎很广泛。有什么方法可以抑制特定字段的警告?还有另一个相关问题 [2],但没有答案。

[1]http://findbugs.sourceforge.net/manual/annotations.html

[2]Suppress FindBugs warnings in Eclipse

演示代码:

public class SyncOnBoxed
{
    static int counter = 0;
    // The following SuppressWarnings does NOT prevent the FindBugs warning
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE")
    final static Long expiringLock = new Long(System.currentTimeMillis() + 10);
    
    public static void main(String[] args) {
        while (increment(expiringLock)) {
            System.out.println(counter);
        }
    }
    
    // The following SuppressWarnings prevents the FindBugs warning
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE")
    protected static boolean increment(Long expiringLock)
    {
        synchronized (expiringLock) { // <<< FindBugs warning is here: Synchronization on Long in SyncOnBoxed.increment()
            counter++;
        }
        return expiringLock > System.currentTimeMillis(); // return false when lock is expired
    }
}

【问题讨论】:

  • 并非如此。这些示例也仅适用于方法级别。可能 FindBugs 只能这样工作。但是为什么SuppressWarning注解文档又说它的Target也可以是Field。
  • 更糟糕的是,当在 Scala 中抑制警告时(至少对于 Find-Sec-Bugs,它是 FindBugs 的安全插件),有时注释 @SuppressFBWarnings 仅在类级别有效,这是绝对不能接受的。
  • 警告!在原始包装器上同步的代码可能会在未来的 Java 版本中中断,抛出 IllegalMonitorStateException!作为 Valhalla 项目的一部分,它将向 Java 添加自定义值类型,原始包装类将被更改为值类型,并且不再可能对它们进行同步。

标签: java findbugs suppress-warnings


【解决方案1】:

字段上的@SuppressFBWarnings 仅抑制为该字段声明报告的 findbugs 警告,而不是与该字段关联的每个警告。

例如,这会抑制“字段仅设置为空”警告:

@SuppressFBWarnings("UWF_NULL_FIELD")
String s = null;

我认为你能做的最好的是将带有警告的代码隔离到最小的方法中,然后抑制整个方法的警告。

注意:@SuppressWarnings 被标记为 deprecated 以支持 @SuppressFBWarnings

【讨论】:

  • “抑制 [...] 不是与该字段相关的所有警告”的解释似乎是正确的。我会将这个答案标记为正确。不过,对其他读者的警告:正如 TimK 解释的那样,我无法在现场抑制“UWF_NULL_FIELD”。因此,可能必须始终在方法级别进行注释。
  • 别忘了@SuppressWarnings 是一个 findbugs 注释,来自:com.google.code.findbugsannotations 2.0.2
  • 请注意@SuppressWarnings 已被deprecated 替换为@SuppressFBWarnings
  • 啊, 版本已弃用。 java.lang包里的这个注解还是不错的(java 8)。
  • java.lang.SuppressWarnings 无法工作。它具有源代码保留,因此 findbugs 不可见。
【解决方案2】:

检查http://findbugs.sourceforge.net/manual/filter.html#d0e2318 有一个可以与 Method 标签一起使用的 Local 标签。您可以在此处指定应为特定局部变量排除哪个错误。 示例:

<FindBugsFilter>
  <Match>
        <Class name="<fully-qualified-class-name>" />
        <Method name="<method-name>" />
        <Local name="<local-variable-name-in-above-method>" />
        <Bug pattern="DLS_DEAD_LOCAL_STORE" />
  </Match>
</FindBugsFilter>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多