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

Chr*_*ken 24 java findbugs suppress-warnings

我想抑制特定字段或局部变量的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
    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*imK 22

@SuppressFBWarnings 在一个字段上只抑制为该字段声明报告的findbugs警告,而不是与该字段相关的每个警告.

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

@SuppressFBWarnings("UWF_NULL_FIELD")
String s = null;
Run Code Online (Sandbox Code Playgroud)

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

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

  • 请注意,`@ SuppressWarnings`已被[弃用](http://findbugs.sourceforge.net/api/edu/umd/cs/findbugs/annotations/SuppressWarnings.html)并替换为`@ SuppressFBWarnings`. (5认同)
  • 并且不要忘记@SuppressWarnings是来自以下内容的findbugs注释:<dependency> <groupId> com.google.code.findbugs </ groupId> <artifactId> annotations </ artifactId> <version> 2.0.2 </ version> < /依赖性> (4认同)
  • `java.lang.SuppressWarnings`无法正常工作.它具有源保留,因此findbugs不可见. (3认同)