【发布时间】:2013-01-08 07:21:53
【问题描述】:
我想禁止针对特定字段或局部变量的 FindBugs 警告。 FindBugs 记录了Target 可以是Type、Field、Method、Parameter、Constructor、Package 的Package 注释[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