Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

java - How to suppress FindBugs warnings for fields or local variables?

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.

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

[2] Suppress FindBugs warnings in Eclipse

Demo code:

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
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@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.

Note: @SuppressWarnings was marked deprecated in favor of @SuppressFBWarnings


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...