如何抑制字段或局部变量的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。
但是对我来说注释该字段并不起作用,只有当我对方法进行注释时警告才会被抑制。
I would like to suppress FindBugs warnings for specific fields or local variables. FindBugs documents that the Target can be Type, Field, Method, Parameter, Constructor, Package for its edu.umd.cs.findbugs.annotations.SuppressWarning annotation [1]. But it does not work for me to annotate the field, only when I annotate the method the warning gets suppressed.
注释整个方法似乎很宽泛我。有没有办法抑制特定字段的警告?还有另一个相关的问题[2],但没有答案。
Annotating a whole method seems to broad to me. Is there any way to suppress warnings on specific fields? There is another related question [2], but no answer.
[1] http://findbugs.sourceforge.net/manual/annotations.html
演示代码:
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
on a field only suppresses findbugs warnings reported for that field declaration, not every warning associated with that field.
例如,这会禁止仅将字段设置为空警告:
For example, this suppresses the "Field only ever set to null" warning:
@SuppressFBWarnings("UWF_NULL_FIELD")
String s = null;
我认为你能做的最好的事情就是将代码与警告隔离成最小的方法,然后在整个方法上禁止警告。
I think the best you can do is isolate the code with the warning into the smallest method you can, then suppress the warning on the whole method.
注意: @SuppressWarnings
被标记为已弃用,转而支持 @SuppressFBWarnings
Note: @SuppressWarnings
was marked deprecated in favor of @SuppressFBWarnings
这篇关于如何抑制字段或局部变量的FindBugs警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!