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

标签 java findbugs suppress-warnings

我想禁止针对特定字段或局部变量的 FindBugs 警告。 FindBugs 文档中 Target 可以是 Type, Field, Method, Parameter, ConstructorPackage 用于其 edu.umd.cs.findbugs.annotations.SuppressWarning 注释 [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
    }
}

最佳答案

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

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

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

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

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

关于java - 如何抑制字段或局部变量的 FindBugs 警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14503001/

相关文章:

java - Spring集成:@Header参数的可配置名称?

java - 如何修复 findbugs "Method accesses list or array with constant index"发现的错误

java - 从 findbugs 隐藏非 java 类

java - 有没有办法对方法的声明声明 suppresswarnings ?

intellij-idea - 全局禁止 NOTHING_TO_INLINE 警告

java - 这些随机数生成不是在 Java 中等效的范围内吗?

Java - 计算存储在数组中的成绩平均值+打印低于平均值的成绩

gwt - FindBugs 通过 GWT 项目在 Jenkins 中给出错误

c# - 在 VS Code 中禁用特定的编译器警告

java - "this"将其作为参数传递给 RMI 时引用发生变化