Detectors

This document lists all detectors in SpotBugs.

Standard detectors

These detectors are on by default:

OverridingMethodsMustInvokeSuperDetector

Finds overriding methods that must call super.

FindRoughConstants

Finds constants which roughly (but not precisely) equal to known values like Math.PI.

SynchronizeAndNullCheckField

This detector looks for a field that is synchronized on and then null checked.

InitializeNonnullFieldsInConstructor

Finds non-null fields that are not written to in constructors.

BooleanReturnNull

Looks for methods with Boolean return type that return explicit null values.

OptionalReturnNull

Looks for methods with Optional return type that return explicit null values.

ConfusionBetweenInheritedAndOuterMethod

Looks for potential confusion between inherited and outer methods.

SynchronizationOnSharedBuiltinConstant

This detector looks for synchronization on a shared built-in constant (such as a String).

NoteUnconditionalParamDerefs

Analyze all methods in the application to determine which dereference parameters unconditionally. This information is used in a later analysis pass to find call sites where null values may be passed to those methods.

This is a slow detector.

SynchronizeOnClassLiteralNotGetClass

Looks for code that synchronizes on the results of getClass rather than on class literals.

InfiniteRecursiveLoop

Looks for an infinite recursive loop.

InfiniteLoop

Looks for an infinite loop.

VolatileUsage

Looks for bug patterns in the usage of volatile fields.

InheritanceUnsafeGetResource

Looks for uses of this.getClass().getResource(...), which can give unexpected results if the class is extended by a class in another package.

DoInsideDoPrivileged

Looks for code that should be executed inside doPrivileged blocks.

HugeSharedStringConstants

This detector looks for string constants that are duplicated across multiple classfiles.

FinalizerNullsFields

This detector looks for finalizers that null out fields of a class. This does not help the garbage collector in any way, the nulling out of fields has no effect.

MutableEnum

Looks and warns about mutable enum fields.

InconsistentAnnotations

This detector finds inconsistencies between type qualifiers directly applied to method parameters and uses of those method parameters.

RepeatedConditionals

This detector looks for code containing repeated conditional tests, such as (x == 5 || x == 5).

RedundantConditions

This detector looks for code containing useless conditions like the second condition in this expression: (x >= 10 && x >= 5).

FormatStringChecker

Checks for incorrect format strings.

LostLoggerDueToWeakReference

This detector finds code that behaves differently under OpenJDK 6, where weak references are used to hold onto Loggers.

EqualsOperandShouldHaveClassCompatibleWithThis

Checks for equals methods that check for their operand being an instance of a class that is not compatible with the class defining the equals method.

CheckImmutableAnnotation

Looks for violations of the rules for classes annotated as net.jcip.annotations.Immutable or javax.annotation.concurrent.Immutable.

DontCatchIllegalMonitorStateException

This detector looks for try-catch blocks that catch an IllegalMonitorStateException.

CloneIdiom

This detector looks for violations of the idioms for writing cloneable classes.

ComparatorIdiom

This detector looks for violations of the idioms for writing classes that implement Comparator.

FindFieldSelfAssignment

This detector looks for places where a field is assigned by reading the value of the same field.

FindSelfComparison

This detector looks for places where a value is compared with itself.

FindSelfComparison2

This detector looks for places where a value is compared with itself.

DroppedException

This detector looks for code where an exception is caught, but nothing is done to handle the exception.

LoadOfKnownNullValue

Looks for loads of values known to be null.

DumbMethodInvocations

This detector looks for bad arguments being passed to methods (e.g., substring(0)).

URLProblems

The equals and hashCode method on java.net.URL resolve the domain name. As a result, these operations can be very expensive, and this detector looks for places where those methods might be invoked.

DumbMethods

This detector looks for calls to pointless methods, such as the no-argument String constructor.

NumberConstructor

Looks for calls to Number constructors with primitive arguments.

FindSqlInjection

This detector uses data flow analysis to look for invocations of execute methods on SQL statements in which something other than a constant string is passed as an argument.

FindDoubleCheck

This detector looks for instances of double-checked locking.

FindFinalizeInvocations

This detector looks for calls to finalize() and other finalizer-related issues.

FindHEmismatch

This detector looks for problems in the definition of the hashCode() and equals() methods.

OverridingEqualsNotSymmetrical

Looks for equals methods that override equals methods in a superclass where the equivalence relationship might not be symmetrical.

FindNakedNotify

This detector looks for calls to notify() that don't seem to modify mutable object state.

FindReturnRef

This detector looks for methods that return mutable static data.

FindRunInvocations

This detector looks for calls to Thread.run(). It is a fast detector.

SwitchFallthrough

This detector looks for switch statements containing fall through.

FindSpinLoop

This detector looks for loops that spin reading from a field.

FindNonShortCircuit

This detector looks for suspicious uses of non-short-circuiting boolean operators (| and & instead of || and &&).

FindTwoLockWait

This detector looks for calls to wait() with two (or more) locks held. It is a slow detector.

FindUnconditionalWait

This detector looks for calls to wait() not in a conditional or loop.

FindUninitializedGet

This detector looks for reads of uninitialized fields in constructors.

DontUseEnum

Checks that fields and methods don't use the name assert or enum as they are keywords in Java 5.

FindUnsyncGet

This detector looks for get and set methods where the get is unsynchronized while the set is synchronized.

InitializationChain

This detector looks for potentially circular class initialization dependencies.

IteratorIdioms

This detector looks for problems in how Iterator classes are defined.

PreferZeroLengthArrays

This detector looks for methods that return either arrays or an explicit null reference. Returning a zero length array is generally preferred in this context to returning a null reference.

SynchronizingOnContentsOfFieldToProtectField

This detector looks for code that seems to be synchronizing on a field in order to guard updates of that field.

MutableLock

This detector looks for synchronization on objects read from modified fields.

FindUselessObjects

Looks for useless objects.

MutableStaticFields

This detector looks for static fields that may be modified by malicious code.

Naming

This detector looks for suspiciously-named methods.

ReadReturnShouldBeChecked

This detector looks for calls to InputStream.read() or InputStream.skip() where the return value is ignored.

SerializableIdiom

This detector looks for potential problems in the implementation of Serializable classes.

StartInConstructor

This detector looks for constructors that start threads.

FindBadForLoop

This detector looks for incorrect for loops.

ExplicitSerialization

Looks for explicit serialization via readObject and writeObject as evidence that this class is, indeed, serialized.

  • :ref:``

UnreadFields

This detector looks for fields whose value is never read.

WaitInLoop

This detector looks for calls to wait() that are not in a loop.

FindComparatorProblems

This detector looks for problems in Comparator.compare or Comparable.compareTo implementation.

FindNullDeref

This detector looks for places where a null pointer exception might occur. It also looks for redundant comparisons of reference values against null. It is a slow detector.

FindNullDerefsInvolvingNonShortCircuitEvaluation

This detector looks for places where a null pointer exception might occur, and the use of non-short-circuit evaluation causes the usual techniques to fail.

FindOpenStream

This detector looks for IO stream objects which do not escape the method and do not appear to be closed on all paths out of the method. It is a slow detector.

FindUselessControlFlow

This detector looks for control flow statements which have no effect.

FindUnreleasedLock

This detector looks for JSR-166 (java.util.concurrent) locks which are acquired, but not released on all paths out of the method.  It is a moderately fast detector.  Note that in order to use this detector, you need to have the java.util.concurrent package in the auxiliary classpath (or be analyzing the package itself).

FindRefComparison

This detector looks for places where two reference values are compared with the == or != operator, and the class is of a type (such as java.lang.String) where comparing reference values is generally an error. It is a slow detector.

FindMismatchedWaitOrNotify

This detector looks for calls to wait(), notify(), or notifyAll() which do not appear to be made on an object which is currently locked.  It is a moderately fast detector.  This detector is disabled because it is still under development, and produces too many false positives.

FindEmptySynchronizedBlock

This detector looks for empty synchronized blocks.

FindInconsistentSync2

This detector looks for fields that are accessed in an inconsistent manner with respect to locking. It is a slow detector.

FindLocalSelfAssignment2

This detector looks for self assignments of local variables.

IncompatMask

This detector looks for suspicious bitwise logical expressions.

LazyInit

This detector looks for lazy field initialization where the field is not volatile. It is a moderately fast detector.

FindJSR166LockMonitorenter

This detector looks for ordinary synchronization performed on JSR166 locks. It is a moderately fast detector.

FindUncalledPrivateMethods

This detector looks for private methods that are never called.

UncallableMethodOfAnonymousClass

This detector looks for anonymous inner classes that define methods that are probably intended to but do not override methods in a superclass.

StringConcatenation

This detector looks for String concatenation in loops using +.

InvalidJUnitTest

This detector looks for JUnit tests that are malformed.

BadlyOverriddenAdapter

This detector looks for code that extends an Adapter class and overrides a Listener method with the wrong signature.

BadResultSetAccess

This detector looks for calls to getXXX or setXXX methods of a result set where the field index is 0. As ResultSet fields start at index 1, this is always a mistake.

SuperfluousInstanceOf

This detector looks for type checks using the instanceof operator where the determination can be done statically.

SuspiciousThreadInterrupted

This detector looks for calls to Thread.interrupted() from a non-static context. If it is called from Thread.currentThread().interrupted(), then it is just a useless exercise, just use Thread.interrupted(). However if it is called on an arbitrary thread object, it is most probably an error, as interrupted() is always called on the current thread.

FindDeadLocalStores

This detector looks for assignments to local variables that are never subsequently read. It is a moderately fast detector.

FindMaskedFields

This detector looks for class level fields that are masked by local fields defined in methods.

WrongMapIterator

This detector looks for accessing the value of a Map entry, using a key that was retrieved from a keySet iterator.

InstantiateStaticClass

This detector looks for code that creates objects based on classes that only define static methods.

RuntimeExceptionCapture

This detector looks for catch clauses that catch Exception, when no code in the block throws Exception.

DontCatchNullPointerException

Nullpointer exceptions should not be caught.

FindFloatEquality

Looks for floating point equality expressions. A fast detector.

FindUnsatisfiedObligation

This detector looks for I/O streams and database resources that are not cleaned up on all paths out of a method. This is a slow detector.

UnnecessaryMath

This detector looks for code that calls java.lang.Math static methods on constant values, where the resultant value is a statically known constant. It is faster, and sometimes more accurate, to use the constant instead.

RedundantInterfaces

This detector looks for classes that declare they implement the same interface as a super class. This is redundant, if a superclass implements an interface, so does the subclass.

MultithreadedInstanceAccess

This detector looks for potential problems in implementing the Struts framework.

BadUseOfReturnValue

Looks for cases where the return value of a function is discarded after being checked for non-null.

MethodReturnCheck

This detector looks for calls to methods where the return value is suspiciously ignored.

IDivResultCastToDouble

This detector looks for places where the result of integer division is cast to double. Often, what was meant was to cast the integer operands to double and then perform the division.

FindBadCast2

This detector looks for bad casts of object references using data flow analysis.

FindUseOfNonSerializableValue

This detector looks for uses of non Serializable objects in contexts that require them to be serializable.

BadSyntaxForRegularExpression

This detector looks for regular expressions that have invalid syntax.

VarArgsProblems

Looks for problems with arising from Java 5 varargs.

FindPuzzlers

This detector looks for miscellaneous small errors mentioned by Joshua Bloch and Neal Gafter in their work on Programming Puzzlers.

IntCast2LongAsInstant

Finds uses of 32-bit values to describe milliseconds since the epoch.

FindSleepWithLockHeld

This detector looks for calls to Thread.sleep() made with a lock held. It is a slow detector.

DuplicateBranches

This detector looks for if/else or switch statements that have the same code for two branches, thus rendering the test useless. This often is caused by copying and pasting the two branches, causing incorrect logic for the one branch.

XMLFactoryBypass

This detector looks for direct allocations of implementations of XML interfaces. This ties the code to a specific implementation, rather than using the supplied factory pattern to create these objects.

ConfusedInheritance

This detector looks for final classes that declare protected members. As this class cannot be derived from, the use of protected access for members is incorrect. The access should be changed to public or private to represent the correct intention of the field. This was probably caused by a change in use for this class, without completely changing all of the class to the new paradigm.

QuestionableBooleanAssignment

This detector looks for simple assignments of literal boolean values to variables in conditional expressions.

AppendingToAnObjectOutputStream

Looks for an attempt to append to an object output stream.

FindUnrelatedTypesInGenericContainer

This detector looks at the arguments of calls to generic collection methods that receive a java.lang.Object to see if the argument's type is related to the collection's parameter. Arguments with unrelated class types are never going to be in the collection. For example, if foo is a List<String> and bar is a StringBuffer, the call foo.contains(bar) will always return false. This is a fast detector.

StaticCalendarDetector

This detector warns about static fields of type java.util.Calendar or java.text.DateFormat (and subclasses) because Calendars are inherently unsafe for multithreaded use.

CheckTypeQualifiers

Check for violations of properties specified by JSR-305 type qualifier annotations.

CrossSiteScripting

This detector looks for obvious/blatant cases of cross site scripting vulnerabilities.

DontIgnoreResultOfPutIfAbsent

Checks that if the result of putIfAbsent is ignored, the value passed as the second argument is not reused.

ReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass

Checks for methods invoked from constructors for superclasses.

AtomicityProblem

Finds sequences of operations (e.g., get/put) on a concurrent abstraction that will not be executed atomically.

DefaultEncodingDetector

Checks for calls to methods which perform a byte to String (or String to byte) conversion using the user's default platform encoding. This can cause the application behavior to vary between platforms.

CheckRelaxingNullnessAnnotation

Checks that overriding methods do not relax @Nonnull (made @CheckForNull) on return values or @CheckForNull (made @Nonnull) on parameters.

DontAssertInstanceofInTests

Detector for patterns in JUnit tests where the type of an object is checked by asserting the instanceof operator.

This should be avoided as the ClassCastException that would result from an improper cast may provide more information regarding the cause of the error than a "false is not true" message which would result from asserting the result of the instanceof operator.

It is a fast detector

FindBadEndOfStreamCheck

Detector for patterns where the return value of java.io.FileInputStream.read() or java.io.FileReader.read() is converted before checking against -1.

Both methods return an int. If this int is converted to byte (in the case of FileInputStream.read()) then -1 and the byte 0xFF become indistinguishable. If it is converted to char (in the case of FileReader.read()) then -1 becomes 0xFFFF which is Character.MAX_VALUE since characters are unsigned in Java.

ReflectionIncreaseAccessibility

Detector for public methods instantiating a class they get in their parameter.

An attacker may invoke this method with a class that has no public constructor.

FindOverridableMethodCall

Detector for patterns where a constructor, a clone(), or a readObject() method calls an overridable method.

Calling an overridable method from a constructor may result in the use of uninitialized data. Calling such method from a clone(), or readObject() method is insecure.

ConstructorThrow

Finds constructors that throw exceptions.

FindInstanceLockOnSharedStaticData

Detector for patterns where a shared static data is modified by either an instance level non-static synchronized method, or inside a synchronized block, which used a non-static lock object.

Programs must not use instance locks to protect static shared data because instance locks are ineffective when two or more instances of the class are created. Consequently, failure to use a static lock object leaves the shared state unprotected against concurrent access.

DontUseFloatsAsLoopCounters

Checks for floats in loop counters.

PermissionsSuper

Checks method getPermissions() of classes implementing interface java.security.SecureClassLoader. The methods must always call super.getPermissions() to get the initial value of the object which they return at the end.

FindPotentialSecurityCheckBasedOnUntrustedSource

Looks for potential security checks on an untrusted source before entering a doPrivileged block.

FindAssertionsWithSideEffects

Finds assertions with side effects.

FindPublicAttributes

This detector looks for public attributes that are also written by the methods of the class.

FindVulnerableSecurityCheckMethods

Methods that perform security checks should be prevented from being overridden, so they must be declared as private or final. Otherwise, these methods can be compromised when a malicious subclass overrides them and omits the checks.

FindArgumentAssertions

Finds assertions that validate public method arguments.

UnnecessaryEnvUsage

Checks for calls of System.getenv(), where the variable has an equivalent Java property too.

MultipleInstantiationsOfSingletons

This detector looks for violations of the idioms for writing classes using singleton design pattern.

Disabled detectors

These detectors are off by default:

EmptyZipFileEntry

This looks for creation of empty ZIP file entries. It is a moderately fast detector.

CallToUnsupportedMethod

This detector looks for calls to methods that are unsupported.

CovariantArrayAssignment

This detector looks for covariant array assignments like Object[] array = new String[10] which may cause ArrayStoreException at runtime.

InefficientInitializationInsideLoop

This detector looks for objects initialized within loop which can be moved outside for better performance.

InefficientIndexOf

This detector looks for code that uses String.indexOf(String) or String.lastIndexOf(String), passing a constant string of length 1. It is recommended to use the more efficient integer implementations. A fast detector.

InefficientToArray

This detector looks for code that converts Collections to arrays using the toArray() method that takes a prototype array, passing an array argument which is zero-length.

BadAppletConstructor

This detector looks for Applet constructors that call methods in the parent Applet that rely on the Applet stub. Since this stub isn't initialized until just before the init() method, these methods will fail in the constructor.

FindCircularDependencies

This detector looks for circular dependencies among classes.

PublicSemaphores

This detector looks for public classes that synchronize and use wait(), notify() or notifyAll() on this. This exposes a synchronization implementation as a public artifact of the class. Clients of the class may use an instance of the class as its own synchronizing object, and cause havoc to the base implementation.

InefficientMemberAccess

This detector looks for internal classes that write to member variables of the owning class, when that member variable is private. In this case, a special compiler generated accessor method needs to be used to write to this variable. Relaxing the visibility to protected will allow the field to be directly written.

UselessSubclassMethod

This detector looks for subclasses that implement methods defined in the super class, that only pass the parameters untouched to the parent class method. These methods can just be removed.

CheckExpectedWarnings

Checks @ExpectedWarning and @NoWarning annotations. This detector is used only for testing SpotBugs.

ThrowingExceptions

This detector looks for methods throwing RuntimeException and methods that have Exception or Throwable in their throws clause.

DontReusePublicIdentifiers

Checks for reuse of public identifiers, public utility classes, interfaces, or packages in the Java Standard Library.