繁体   English   中英

如何抑制字段或局部变量的FindBugs警告

[英]How to suppress FindBugs warnings for fields or local variables

我想抑制特定字段或局部变量的FindBugs警告。 FindBugs文档指出Target的edu.umd.cs.findbugs.annotations.SuppressWarning注释[1]可以是Type,Field,Method,Parameter,Constructor,Package。 但是,只有当我注释警告被抑制的方法时,它才能对我进行注释。

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

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

[2] 在Eclipse中抑制FindBugs警告

演示代码:

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
    }
}

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

例如,这会禁止“仅将字段设置为空”警告:

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

我认为你能做的最好的事情是将代码与警告隔离到最小的方法中,然后在整个方法上禁止警告。

注意: @SuppressWarnings被标记为已弃用 ,有利于@SuppressFBWarnings

检查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>

暂无
暂无

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

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