This list is auto-generated from our sources. Each bug pattern includes code examples of both positive and negative cases; these examples are used in our regression test suite.
Patterns which are marked Experimental will not be evaluated against your code, unless you specifically configure Error Prone. The default checks are marked On by default, and each release promotes some experimental checks after we’ve vetted them against Google’s codebase.
AndroidInjectionBeforeSuper
AndroidInjection.inject() should always be invoked before calling super.lifecycleMethod()
ArrayEquals
Reference equality used to compare arrays
ArrayFillIncompatibleType
Arrays.fill(Object[], Object) called with incompatible types.
ArrayHashCode
hashcode method on array does not hash array contents
ArrayToString
Calling toString on an array does not provide useful information
ArraysAsListPrimitiveArray
Arrays.asList does not autobox primitive arrays, as one might expect.
AsyncCallableReturnsNull
AsyncCallable should not return a null Future, only a Future whose result is null.
AsyncFunctionReturnsNull
AsyncFunction should not return a null Future, only a Future whose result is null.
AutoValueConstructorOrderChecker
Arguments to AutoValue constructor are in the wrong order
BadShiftAmount
Shift by an amount that is out of range
BundleDeserializationCast
Object serialized in Bundle may have been flattened to base type.
ChainingConstructorIgnoresParameter
The called constructor accepts a parameter with the same name and type as one of its caller's parameters, but its caller doesn't pass that parameter to it. It's likely that it was intended to.
CheckNotNullMultipleTimes
A variable was checkNotNulled multiple times. Did you mean to check something else?
CheckReturnValue
Ignored return value of method that is annotated with @CheckReturnValue
CollectionIncompatibleType
Incompatible type as argument to Object-accepting Java collections method
CollectionToArraySafeParameter
The type of the array parameter of Collection.toArray needs to be compatible with the array type
ComparableType
Implementing 'Comparable<T>' where T is not the same as the implementing class is incorrect, since it violates the symmetry contract of compareTo.
ComparingThisWithNull
this == null is always false, this != null is always true
ComparisonOutOfRange
Comparison to value that is out of range for the compared type
CompatibleWithAnnotationMisuse
@CompatibleWith's value is not a type argument.
CompileTimeConstant
Non-compile-time constant expression passed to parameter with @CompileTimeConstant type annotation.
ConditionalExpressionNumericPromotion
A conditional expression with numeric operands of differing types will perform binary numeric promotion of the operands; when these operands are of reference types, the expression's result may not be of the expected type.
ConstantOverflow
Compile-time constant expression overflows
DaggerProvidesNull
Dagger @Provides methods may not return null unless annotated with @Nullable
DeadException
Exception created but not thrown
DeadThread
Thread created but not started
DiscardedPostfixExpression
The result of this unary operation on a lambda parameter is discarded
DoNotCall
This method should not be called.
DoNotMock
Identifies undesirable mocks.
DuplicateMapKeys
Map#ofEntries will throw an IllegalArgumentException if there are any duplicate keys
DurationFrom
Duration.from(Duration) returns itself; from(Period) throws a runtime exception.
DurationGetTemporalUnit
Duration.get() only works with SECONDS or NANOS.
DurationTemporalUnit
Duration APIs only work for DAYS or exact durations.
DurationToLongTimeUnit
Unit mismatch when decomposing a Duration or Instant to call a <long, TimeUnit> API
EqualsHashCode
Classes that override equals should also override hashCode.
EqualsNaN
== NaN always returns false; use the isNaN methods instead
EqualsReference
== must be used in equals method to check equality to itself or an infinite loop will occur.
EqualsWrongThing
Comparing different pairs of fields/getters in an equals implementation is probably a mistake.
ExtendsAutoValue
Do not extend an @AutoValue/@AutoOneOf class in non-generated code.
ForOverride
Method annotated @ForOverride must be protected or package-private and only invoked from declaring class, or from an override of the method
FormatString
Invalid printf-style format string
FormatStringAnnotation
Invalid format string passed to formatting method.
FunctionalInterfaceMethodChanged
Casting a lambda to this @FunctionalInterface can cause a behavior change from casting to a functional superinterface, which is surprising to users. Prefer decorator methods to this surprising behavior.
FuturesGetCheckedIllegalExceptionType
Futures.getChecked requires a checked exception type with a standard constructor.
GetClassOnAnnotation
Calling getClass() on an annotation may return a proxy class
GetClassOnClass
Calling getClass() on an object of type Class returns the Class object for java.lang.Class; you probably meant to operate on the object directly
GuardedBy
Checks for unguarded accesses to fields and methods with @GuardedBy annotations
GuiceAssistedInjectScoping
Scope annotation on implementation class of AssistedInject factory is not allowed
GuiceAssistedParameters
A constructor cannot have two @Assisted parameters of the same type unless they are disambiguated with named @Assisted annotations.
GuiceInjectOnFinalField
Although Guice allows injecting final fields, doing so is disallowed because the injected value may not be visible to other threads.
HashtableContains
contains() is a legacy method that is equivalent to containsValue()
IdentityBinaryExpression
A binary expression where both operands are the same is usually incorrect.
Immutable
Type declaration annotated with @Immutable is not immutable
ImmutableModification
Modifying an immutable collection is guaranteed to throw an exception and leave the collection unmodified
Incomparable
Types contained in sorted collections must implement Comparable.
IncompatibleArgumentType
Passing argument to a generic method with an incompatible type.
IncompatibleModifiers
This annotation has incompatible modifiers as specified by its @IncompatibleModifiers annotation
IndexOfChar
The first argument to indexOf is a Unicode code point, and the second is the index to start the search from
InexactVarargsConditional
Conditional expression in varargs call contains array and non-array arguments
InfiniteRecursion
This method always recurses, and will cause a StackOverflowError
InjectMoreThanOneScopeAnnotationOnClass
A class can be annotated with at most one scope annotation.
InjectOnMemberAndConstructor
Members shouldn't be annotated with @Inject if constructor is already annotated @Inject
InstantTemporalUnit
Instant APIs only work for NANOS, MICROS, MILLIS, SECONDS, MINUTES, HOURS, HALF_DAYS and DAYS.
InvalidJavaTimeConstant
This checker errors on calls to java.time methods using values that are guaranteed to throw a DateTimeException.
InvalidPatternSyntax
Invalid syntax used for a regular expression
InvalidTimeZoneID
Invalid time zone identifier. TimeZone.getTimeZone(String) will silently return GMT instead of the time zone you intended.
InvalidZoneId
Invalid zone identifier. ZoneId.of(String) will throw exception at runtime.
IsInstanceOfClass
The argument to Class#isInstance(Object) should not be a Class
IsLoggableTagLength
Log tag too long, cannot exceed 23 characters.
JUnit3TestNotRun
Test method will not be run; please correct method signature (Should be public, non-static, and method name should begin with "test").
JUnit4ClassAnnotationNonStatic
This method should be static
JUnit4SetUpNotRun
setUp() method will not be run; please add JUnit's @Before annotation
JUnit4TearDownNotRun
tearDown() method will not be run; please add JUnit's @After annotation
JUnit4TestNotRun
This looks like a test method but is not run; please add @Test and @Ignore, or, if this is a helper method, reduce its visibility.
JUnitAssertSameCheck
An object is tested for reference equality to itself using JUnit library.
JavaxInjectOnAbstractMethod
Abstract and default methods are not injectable with javax.inject.Inject
JodaToSelf
Use of Joda-Time's DateTime.toDateTime(), Duration.toDuration(), Instant.toInstant(), Interval.toInterval(), and Period.toPeriod() are not allowed.
LiteByteStringUtf8
This pattern will silently corrupt certain byte sequences from the serialized protocol message. Use ByteString or byte[] directly
LocalDateTemporalAmount
LocalDate.plus() and minus() does not work with Durations. LocalDate represents civil time (years/months/days), so java.time.Period is the appropriate thing to add or subtract instead.
LoopConditionChecker
Loop condition is never modified in loop body.
MathRoundIntLong
Math.round(Integer) results in truncation
MislabeledAndroidString
Certain resources in android.R.string
have names that do not match their content
MissingSuperCall
Overriding method is missing a call to overridden super method
MissingTestCall
A terminating method call is required for a test helper to have any effect.
MisusedWeekYear
Use of "YYYY" (week year) in a date pattern without "ww" (week in year). You probably meant to use "yyyy" (year) instead.
MockitoCast
A bug in Mockito will cause this test to fail at runtime with a ClassCastException
MockitoUsage
Missing method call for verify(mock) here
ModifyingCollectionWithItself
Using a collection function with itself as the argument.
MoreThanOneInjectableConstructor
This class has more than one @Inject-annotated constructor. Please remove the @Inject annotation from all but one of them.
MustBeClosedChecker
The result of this method must be closed.
NCopiesOfChar
The first argument to nCopies is the number of copies, and the second is the item to copy
NonCanonicalStaticImport
Static import of type uses non-canonical name
NonFinalCompileTimeConstant
@CompileTimeConstant parameters should be final or effectively final
NonRuntimeAnnotation
Calling getAnnotation on an annotation that is not retained at runtime.
NullTernary
This conditional expression may evaluate to null, which will result in an NPE when the result is unboxed.
OptionalEquality
Comparison using reference equality instead of value equality
OverlappingQualifierAndScopeAnnotation
Annotations cannot be both Scope annotations and Qualifier annotations: this causes confusion when trying to use them.
OverridesJavaxInjectableMethod
This method is not annotated with @Inject, but it overrides a method that is annotated with @javax.inject.Inject. The method will not be Injected.
PackageInfo
Declaring types inside package-info.java files is very bad form
ParametersButNotParameterized
This test has @Parameters but is using the default JUnit4 runner. The parameters will have no effect.
ParcelableCreator
Detects classes which implement Parcelable but don't have CREATOR
PeriodFrom
Period.from(Period) returns itself; from(Duration) throws a runtime exception.
PeriodGetTemporalUnit
Period.get() only works with YEARS, MONTHS, or DAYS.
PeriodTimeMath
When adding or subtracting from a Period, Duration is incompatible.
PredicateIncompatibleType
Using ::equals or ::isInstance as an incompatible Predicate; the predicate will always return false
PrivateSecurityContractProtoAccess
Access to a private protocol buffer field is forbidden. This protocol buffer carries a security contract, and can only be created using an approved library. Direct access to the fields is forbidden.
ProtoFieldNullComparison
Protobuf fields cannot be null.
ProtoStringFieldReferenceEquality
Comparing protobuf fields of type String using reference equality
ProtoTruthMixedDescriptors
The arguments passed to ignoringFields
are inconsistent with the proto which is the subject of the assertion.
ProtocolBufferOrdinal
To get the tag number of a protocol buffer enum, use getNumber() instead.
ProvidesMethodOutsideOfModule
@Provides methods need to be declared in a Module to have any effect.
RandomCast
Casting a random number in the range [0.0, 1.0) to an integer or long always results in 0.
RandomModInteger
Use Random.nextInt(int). Random.nextInt() % n can have negative results
RectIntersectReturnValueIgnored
Return value of android.graphics.Rect.intersect() must be checked
RefersToDaggerCodegen
Don't refer to Dagger's internal or generated code
RestrictedApiChecker
Check for non-whitelisted callers to RestrictedApiChecker.
ReturnValueIgnored
Return value of this method must be used
SelfAssignment
Variable assigned to itself
SelfComparison
An object is compared to itself
SelfEquals
Testing an object for equality with itself will always be true.
ShouldHaveEvenArgs
This method must be called with an even number of arguments.
SizeGreaterThanOrEqualsZero
Comparison of a size >= 0 is always true, did you intend to check for non-emptiness?
StreamToString
Calling toString on a Stream does not provide useful information
StringBuilderInitWithChar
StringBuilder does not have a char constructor; this invokes the int constructor.
SubstringOfZero
String.substring(0) returns the original String
SuppressWarningsDeprecated
Suppressing "deprecated" is probably a typo for "deprecation"
TemporalAccessorGetChronoField
TemporalAccessor.get() only works for certain values of ChronoField.
TheoryButNoTheories
This test has members annotated with @Theory, @DataPoint, or @DataPoints but is using the default JUnit4 runner.
ThrowIfUncheckedKnownChecked
throwIfUnchecked(knownCheckedException) is a no-op.
ThrowNull
Throwing 'null' always results in a NullPointerException being thrown.
TruthSelfEquals
isEqualTo should not be used to test an object for equality with itself; the assertion will never fail.
TryFailThrowable
Catching Throwable/Error masks failures from fail() or assert*() in the try block
TypeParameterQualifier
Type parameter used as type qualifier
UnnecessaryCheckNotNull
This null check is unnecessary; the expression can never be null
UnnecessaryTypeArgument
Non-generic methods should not be invoked with type arguments
UnusedAnonymousClass
Instance created but never used
UnusedCollectionModifiedInPlace
Collection is modified in place, but the result is not used
VarTypeName
var
should not be used as a type name.
XorPower
The ^
operator is binary XOR, not a power operator.
AmbiguousMethodReference
Method reference is ambiguous
AnnotateFormatMethod
This method passes a pair of parameters through to String.format, but the enclosing method wasn't annotated @FormatMethod. Doing so gives compile-time rather than run-time protection against malformed format strings.
ArgumentSelectionDefectChecker
Arguments are in the wrong order or could be commented for clarity.
ArrayAsKeyOfSetOrMap
Arrays do not override equals() or hashCode, so comparisons will be done on reference equality only. If neither deduplication nor lookup are needed, consider using a List instead. Otherwise, use IdentityHashMap/Set, a Map from a library that handles object arrays, or an Iterable/List of pairs.
AssertEqualsArgumentOrderChecker
Arguments are swapped in assertEquals-like call
AssertThrowsMultipleStatements
The lambda passed to assertThrows should contain exactly one statement
AssertionFailureIgnored
This assertion throws an AssertionError if it fails, which will be caught by an enclosing try block.
AssignmentToMock
Fields annotated with @Mock should not be manually assigned to.
AutoValueFinalMethods
Make toString(), hashCode() and equals() final in AutoValue classes, so it is clear to readers that AutoValue is not overriding them
AutoValueImmutableFields
AutoValue recommends using immutable collections
BadAnnotationImplementation
Classes that implement Annotation must override equals and hashCode. Consider using AutoAnnotation instead of implementing Annotation by hand.
BadComparable
Possible sign flip from narrowing conversion
BadImport
Importing nested classes/static methods/static fields with commonly-used names can make code harder to read, because it may not be clear from the context exactly which type is being referred to. Qualifying the name with that of the containing class can make the code clearer.
BadInstanceof
instanceof used in a way that is equivalent to a null check.
BigDecimalEquals
BigDecimal#equals has surprising behavior: it also compares scale.
BigDecimalLiteralDouble
new BigDecimal(double) loses precision in this case.
BoxedPrimitiveConstructor
valueOf or autoboxing provides better time and space performance
BoxedPrimitiveEquality
Comparison using reference equality instead of value equality. Reference equality of boxed primitive types is usually not useful, as they are value objects, and it is bug-prone, as instances are cached for some values but not others.
ByteBufferBackingArray
ByteBuffer.array() shouldn't be called unless ByteBuffer.arrayOffset() is used or if the ByteBuffer was initialized using ByteBuffer.wrap() or ByteBuffer.allocate().
CannotMockFinalClass
Mockito cannot mock final classes
CanonicalDuration
Duration can be expressed more clearly with different units
CatchAndPrintStackTrace
Logging or rethrowing exceptions should usually be preferred to catching and calling printStackTrace
CatchFail
Ignoring exceptions and calling fail() is unnecessary, and makes test output less useful
ChainedAssertionLosesContext
Inside a Subject, use check(…) instead of assert*() to preserve user-supplied messages and other settings.
ClassCanBeStatic
Inner class is non-static but does not reference enclosing class
ClassNewInstance
Class.newInstance() bypasses exception checking; prefer getDeclaredConstructor().newInstance()
CloseableProvides
Providing Closeable resources makes their lifecycle unclear
CollectorShouldNotUseState
Collector.of() should not use state
ComparableAndComparator
Class should not implement both Comparable
and Comparator
CompareToZero
The result of #compareTo or #compare should only be compared to 0. It is an implementation detail whether a given type returns strictly the values {-1, 0, +1} or others.
ComplexBooleanConstant
Non-trivial compile time constant boolean expressions shouldn't be used.
DateFormatConstant
DateFormat is not thread-safe, and should not be used as a constant field.
DefaultCharset
Implicit use of the platform default charset, which can result in differing behaviour between JVM executions or incorrect behavior if the encoding of the data source doesn't match expectations.
DoubleBraceInitialization
Prefer collection factory methods or builders to the double-brace initialization pattern.
DoubleCheckedLocking
Double-checked locking on non-volatile fields is unsafe
EqualsGetClass
Overriding Object#equals in a non-final class by using getClass rather than instanceof breaks substitutability of subclasses.
EqualsIncompatibleType
An equality test between objects with incompatible types always returns false
EqualsUnsafeCast
The contract of #equals states that it should return false for incompatible types, while this implementation may throw ClassCastException.
EqualsUsingHashCode
Implementing #equals by just comparing hashCodes is fragile. Hashes collide frequently, and this will lead to false positives in #equals.
ExtendingJUnitAssert
When only using JUnit Assert's static methods, you should import statically instead of extending.
FallThrough
Switch case may fall through
Finally
If you return or throw from a finally, then values returned or thrown from the try-catch block will be ignored. Consider using try-with-resources instead.
FloatCast
Use parentheses to make the precedence explicit
FloatingPointAssertionWithinEpsilon
This fuzzy equality check is using a tolerance less than the gap to the next number. You may want a less restrictive tolerance, or to assert equality.
FloatingPointLiteralPrecision
Floating point literal loses precision
FragmentInjection
Classes extending PreferenceActivity must implement isValidFragment such that it does not unconditionally return true to prevent vulnerability to fragment injection attacks.
FragmentNotInstantiable
Subclasses of Fragment must be instantiable via Class#newInstance(): the class must be public, static and have a public nullary constructor
FutureReturnValueIgnored
Return value of methods returning Future must be checked. Ignoring returned Futures suppresses exceptions thrown from the code that completes the Future.
GetClassOnEnum
Calling getClass() on an enum may return a subclass of the enum type
HidingField
Hiding fields of superclasses may cause confusion and errors
ImmutableAnnotationChecker
Annotations should always be immutable
ImmutableEnumChecker
Enums should always be immutable
InconsistentCapitalization
It is confusing to have a field and a parameter under the same scope that differ only in capitalization.
InconsistentHashCode
Including fields in hashCode which are not compared in equals violates the contract of hashCode.
IncrementInForLoopAndHeader
This for loop increments the same variable in the header and in the body
InjectOnConstructorOfAbstractClass
Constructors on abstract classes are never directly @Injected, only the constructors of their subclasses can be @Inject'ed.
InputStreamSlowMultibyteRead
Please also override int read(byte[], int, int), otherwise multi-byte reads from this input stream are likely to be slow.
InstanceOfAndCastMatchWrongType
Casting inside an if block should be plausibly consistent with the instanceof type
IntLongMath
Expression of type int may overflow before being assigned to a long
IterableAndIterator
Class should not implement both Iterable
and Iterator
JUnit3FloatingPointComparisonWithoutDelta
Floating-point comparison without error tolerance
JUnit4ClassUsedInJUnit3
Some JUnit4 construct cannot be used in a JUnit3 context. Convert your class to JUnit4 style to use them.
JUnitAmbiguousTestClass
Test class inherits from JUnit 3's TestCase but has JUnit 4 @Test annotations.
JavaDurationGetSecondsGetNano
duration.getNano() only accesses the underlying nanosecond adjustment from the whole second.
JavaDurationWithNanos
Use of java.time.Duration.withNanos(int) is not allowed.
JavaDurationWithSeconds
Use of java.time.Duration.withSeconds(long) is not allowed.
JavaInstantGetSecondsGetNano
instant.getNano() only accesses the underlying nanosecond adjustment from the whole second.
JavaLangClash
Never reuse class names from java.lang
JavaLocalDateTimeGetNano
localDateTime.getNano() only accesss the nanos-of-second field. It's rare to only use getNano() without a nearby getSecond() call.
JavaLocalTimeGetNano
localTime.getNano() only accesses the nanos-of-second field. It's rare to only use getNano() without a nearby getSecond() call.
JavaPeriodGetDays
period.getDays() only accesses the "days" portion of the Period, and doesn't represent the total span of time of the period. Consider using org.threeten.extra.Days to extract the difference between two civil dates if you want the whole time.
JavaTimeDefaultTimeZone
java.time APIs that silently use the default system time-zone are not allowed.
JdkObsolete
Suggests alternatives to obsolete JDK classes.
JodaDurationConstructor
Use of new Duration(long) is not allowed. Please use Duration.millis(long) instead.
JodaDurationWithMillis
Use of duration.withMillis(long) is not allowed. Please use Duration.millis(long) instead.
JodaInstantWithMillis
Use of instant.withMillis(long) is not allowed. Please use new Instant(long) instead.
JodaNewPeriod
This may have surprising semantics, e.g. new Period(LocalDate.parse("1970-01-01"), LocalDate.parse("1970-02-02")).getDays() == 1, not 32.
JodaPlusMinusLong
Use of JodaTime's type.plus(long) or type.minus(long) is not allowed (where <type> = {Duration,Instant,DateTime,DateMidnight}). Please use type.plus(Duration.millis(long)) or type.minus(Duration.millis(long)) instead.
JodaTimeConverterManager
Joda-Time's ConverterManager makes the semantics of DateTime/Instant/etc construction subject to global static state. If you need to define your own converters, use a helper.
JodaWithDurationAddedLong
Use of JodaTime's type.withDurationAdded(long, int) (where <type> = {Duration,Instant,DateTime}). Please use type.withDurationAdded(Duration.millis(long), int) instead.
LiteEnumValueOf
Instead of converting enums to string and back, its numeric value should be used instead as it is the stable part of the protocol defined by the enum.
LiteProtoToString
toString() on lite protos will not generate a useful representation of the proto from optimized builds. Consider whether using some subset of fields instead would provide useful information.
LockNotBeforeTry
Calls to Lock#lock should be immediately followed by a try block which releases the lock.
LogicalAssignment
Assignment where a boolean expression was expected; use == if this assignment wasn't expected or add parentheses for clarity.
MathAbsoluteRandom
Math.abs does not always give a positive result. Please consider other methods for positive random numbers.
MissingCasesInEnumSwitch
Switches on enum types should either handle all values, or have a default case.
MissingFail
Not calling fail() when expecting an exception masks bugs
MissingOverride
method overrides method in supertype; expected @Override
MixedDescriptors
The field number passed into #getFieldByNumber belongs to a different proto to the Descriptor.
MixedMutabilityReturnType
This method returns both mutable and immutable collections or maps from different paths. This may be confusing for users of the method.
ModifiedButNotUsed
A collection or proto builder was created, but its values were never accessed.
ModifyCollectionInEnhancedForLoop
Modifying a collection while iterating over it in a loop may cause a ConcurrentModificationException to be thrown.
ModifySourceCollectionInStream
Modifying the backing source during stream operations may cause unintended results.
MultipleParallelOrSequentialCalls
Multiple calls to either parallel or sequential are unnecessary and cause confusion.
MutableConstantField
Constant field declarations should use the immutable type (such as ImmutableList) instead of the general collection interface type (such as List)
NarrowingCompoundAssignment
Compound assignments may hide dangerous casts
NestedInstanceOfConditions
Nested instanceOf conditions of disjoint types create blocks of code that never execute
NonAtomicVolatileUpdate
This update of a volatile variable is non-atomic
NonOverridingEquals
equals method doesn't override Object.equals
NullableConstructor
Constructors should not be annotated with @Nullable since they cannot return null
NullablePrimitive
@Nullable should not be used for primitive types since they cannot be null
NullableVoid
void-returning methods should not be annotated with @Nullable, since they cannot return null
ObjectToString
Calling toString on Objects that don't override toString() doesn't provide useful information
ObjectsHashCodePrimitive
Objects.hashCode(Object o) should not be passed a primitive value
OperatorPrecedence
Use grouping parenthesis to make the operator precedence explicit
OptionalMapToOptional
Mapping to another Optional will yield a nested Optional. Did you mean flatMap?
OptionalNotPresent
One should not call optional.get() inside an if statement that checks !optional.isPresent
OrphanedFormatString
String literal contains format specifiers, but is not passed to a format method
OutlineNone
Setting CSS outline style to none or 0 (while not otherwise providing visual focus indicators) is inaccessible for users navigating a web page without a mouse.
OverrideThrowableToString
To return a custom message with a Throwable class, one should override getMessage() instead of toString().
Overrides
Varargs doesn't agree for overridden method
OverridesGuiceInjectableMethod
This method is not annotated with @Inject, but it overrides a method that is annotated with @com.google.inject.Inject. Guice will inject this method, and it is recommended to annotate it explicitly.
ParameterName
Detects /* name= */
-style comments on actual parameters where the name doesn't match the formal parameter
PreconditionsCheckNotNullRepeated
Including the first argument of checkNotNull in the failure message is not useful, as it will always be null
.
PreconditionsInvalidPlaceholder
Preconditions only accepts the %s placeholder in error message strings
PreferJavaTimeOverload
Prefer using java.time-based APIs when available. Note that this checker does not and cannot guarantee that the overloads have equivalent semantics, but that is generally the case with overloaded methods.
PrimitiveAtomicReference
Using compareAndSet with boxed primitives is dangerous, as reference rather than value equality is used. Consider using AtomicInteger, AtomicLong, or AtomicBoolean instead.
ProtoDurationGetSecondsGetNano
getNanos() only accesses the underlying nanosecond-adjustment of the duration.
ProtoRedundantSet
A field on a protocol buffer was set twice in the same chained expression.
ProtoTimestampGetSecondsGetNano
getNanos() only accesses the underlying nanosecond-adjustment of the instant.
QualifierOrScopeOnInjectMethod
Qualifiers/Scope annotations on @Inject methods don't have any effect. Move the qualifier annotation to the binding location.
ReachabilityFenceUsage
reachabilityFence should always be called inside a finally block
ReferenceEquality
Comparison using reference equality instead of value equality
RequiredModifiers
This annotation is missing required modifiers as specified by its @RequiredModifiers annotation
RxReturnValueIgnored
Returned Rx objects must be checked. Ignoring a returned Rx value means it is never scheduled for execution
SameNameButDifferent
This type name shadows another in a way that may be confusing.
ShortCircuitBoolean
Prefer the short-circuiting boolean operators && and || to & and |.
StaticGuardedByInstance
Writes to static fields should not be guarded by instance locks
StreamResourceLeak
Streams that encapsulate a closeable resource should be closed using try-with-resources
StringSplitter
String.split(String) has surprising behavior
SwigMemoryLeak
SWIG generated code that can't call a C++ destructor will leak memory
SynchronizeOnNonFinalField
Synchronizing on non-final fields is not safe: if the field is ever updated, different threads may end up locking on different objects.
ThreadJoinLoop
Thread.join needs to be surrounded by a loop until it succeeds, as in Uninterruptibles.joinUninterruptibly.
ThreadLocalUsage
ThreadLocals should be stored in static fields
ThreadPriorityCheck
Relying on the thread scheduler is discouraged; see Effective Java 3rd Edition Item 84.
ThreeLetterTimeZoneID
Three-letter time zone identifiers are deprecated, may be ambiguous, and might not do what you intend; the full IANA time zone ID should be used instead.
TimeUnitConversionChecker
This TimeUnit conversion looks buggy: converting from a smaller unit to a larger unit (and passing a constant), converting to/from the same TimeUnit, or converting TimeUnits where the result is statically known to be 0 or 1 are all buggy patterns.
ToStringReturnsNull
An implementation of Object.toString() should never return null.
TreeToString
Tree#toString shouldn't be used for Trees deriving from the code being compiled, as it discards whitespace and comments.
TruthAssertExpected
The actual and expected values appear to be swapped, which results in poor assertion failure messages. The actual value should come first.
TruthConstantAsserts
Truth Library assert is called on a constant.
TruthIncompatibleType
Argument is not compatible with the subject's type.
TypeEquals
com.sun.tools.javac.code.Type doesn't override Object.equals and instances are not interned by javac, so testing types for equality should be done with Types#isSameType instead
TypeNameShadowing
Type parameter declaration shadows another named type
TypeParameterShadowing
Type parameter declaration overrides another type parameter already declared
TypeParameterUnusedInFormals
Declaring a type parameter that is only used in the return type is a misuse of generics: operations on the type parameter are unchecked, it hides unsafe casts at invocations of the method, and it interacts badly with method overload resolution.
URLEqualsHashCode
Avoid hash-based containers of java.net.URL–the containers rely on equals() and hashCode(), which cause java.net.URL to make blocking internet connections.
UndefinedEquals
This type is not guaranteed to implement a useful #equals method.
UnnecessaryAnonymousClass
Implementing a functional interface is unnecessary; prefer to implement the functional interface method directly and use a method reference instead.
UnnecessaryLambda
Returning a lambda from a helper method or saving it in a constant is unnecessary; prefer to implement the functional interface method directly and use a method reference instead.
UnnecessaryMethodInvocationMatcher
It is not necessary to wrap a MethodMatcher with methodInvocation().
UnnecessaryParentheses
These grouping parentheses are unnecessary; it is unlikely the code will be misinterpreted without them
UnsafeFinalization
Finalizer may run before native code finishes execution
UnsafeReflectiveConstructionCast
Prefer asSubclass
instead of casting the result of newInstance
, to detect classes of incorrect type before invoking their constructors.This way, if the class is of the incorrect type,it will throw an exception before invoking its constructor.
UnsynchronizedOverridesSynchronized
Unsynchronized method overrides a synchronized method.
UnusedMethod
Unused.
UnusedNestedClass
This nested class is unused, and can be removed.
UnusedVariable
Unused.
UseCorrectAssertInTests
Java assert is used in test. For testing purposes Assert.* matchers should be used.
VariableNameSameAsType
variableName and type with the same name would refer to the static field instead of the class
WaitNotInLoop
Because of spurious wakeups, Object.wait() and Condition.await() must always be called in a loop
WakelockReleasedDangerously
A wakelock acquired with a timeout may be released by the system before calling release
, even after checking isHeld()
. If so, it will throw a RuntimeException. Please wrap in a try/catch block.
WithSignatureDiscouraged
withSignature is discouraged. Prefer .named and/or .withParameters where possible.
AndroidJdkLibsChecker
Use of class, field, or method that is not compatible with legacy Android devices
AssistedInjectAndInjectOnSameConstructor
@AssistedInject and @Inject cannot be used on the same constructor.
AutoFactoryAtInject
@AutoFactory and @Inject should not be used in the same type.
ClassName
The source file name should match the name of the top-level class it contains
ComparisonContractViolated
This comparison method violates the contract
DeduplicateConstants
This expression was previously declared as a constant; consider replacing this occurrence.
DepAnn
Item documented with a @deprecated javadoc note is not annotated with @Deprecated
DescribeMatch
describeMatch(tree, fix)
is equivalent to and simpler than buildDescription(tree).addFix(fix).build()
DivZero
Division by integer literal zero
EmptyIf
Empty statement after if
FuzzyEqualsShouldNotBeUsedInEqualsMethod
DoubleMath.fuzzyEquals should never be used in an Object.equals() method
InjectInvalidTargetingOnScopingAnnotation
A scoping annotation's Target should include TYPE and METHOD.
InjectMoreThanOneQualifier
Using more than one qualifier annotation on the same element is not allowed.
InjectScopeAnnotationOnInterfaceOrAbstractClass
Scope annotation on an interface or abstract class is not allowed
InjectScopeOrQualifierAnnotationRetention
Scoping and qualifier annotations must have runtime retention.
InjectedConstructorAnnotations
Injected constructors cannot be optional nor have binding annotations
InsecureCryptoUsage
A standard cryptographic operation is used in a mode that is prone to vulnerabilities
IterablePathParameter
Path implements Iterable<Path>; prefer Collection<Path> for clarity
JMockTestWithoutRunWithOrRuleAnnotation
jMock tests must have a @RunWith(JMock.class) annotation, or the Mockery field must have a @Rule JUnit annotation
Java7ApiChecker
Use of class, field, or method that is not compatible with JDK 7
JavaxInjectOnFinalField
@javax.inject.Inject cannot be put on a final field.
LockMethodChecker
This method does not acquire the locks specified by its @LockMethod annotation
LongLiteralLowerCaseSuffix
Prefer 'L' to 'l' for the suffix to long literals
NoAllocation
@NoAllocation was specified on this method, but something was found that would trigger an allocation
NumericEquality
Numeric comparison using reference equality instead of value equality
ParameterPackage
Method parameter has wrong package
StaticOrDefaultInterfaceMethod
Static and default interface methods are not natively supported on older Android devices.
UnlockMethod
This method does not acquire the locks specified by its @UnlockMethod annotation
AlmostJavadoc
This comment contains Javadoc or HTML tags, but isn't started with a double asterisk (/**); is it meant to be Javadoc?
AnnotationPosition
Annotations should be positioned after Javadocs, but before modifiers.
AssertFalse
Assertions may be disabled at runtime and do not guarantee that execution will halt here; consider throwing an exception instead
AssistedInjectAndInjectOnConstructors
@AssistedInject and @Inject should not be used on different constructors in the same class.
BinderIdentityRestoredDangerously
A call to Binder.clearCallingIdentity() should be followed by Binder.restoreCallingIdentity() in a finally block. Otherwise the wrong Binder identity may be used by subsequent code.
BindingToUnqualifiedCommonType
This code declares a binding for a common value type without a Qualifier annotation.
ConstructorInvokesOverridable
Constructors should not invoke overridable methods.
ConstructorLeaksThis
Constructors should not pass the 'this' reference out in method invocations, since the object may not be fully constructed.
EmptyBlockTag
A block tag (@param, @return, @throws, @deprecated) has an empty description. Block tags without descriptions don't add much value for future readers of the code; consider removing the tag entirely or adding a description.
EmptyTopLevelDeclaration
Empty top-level type declaration
EqualsBrokenForNull
equals() implementation may throw NullPointerException when given null
EscapedEntity
HTML entities in @code/@literal tags will appear literally in the rendered javadoc.
ExpectedExceptionChecker
Calls to ExpectedException#expect should always be followed by exactly one statement.
FunctionalInterfaceClash
Overloads will be ambiguous when passing lambda arguments.
HardCodedSdCardPath
Hardcoded reference to /sdcard
InconsistentOverloads
The ordering of parameters in overloaded methods should be as consistent as possible (when viewed from left to right)
InheritDoc
Invalid use of @inheritDoc.
InterfaceWithOnlyStatics
This interface only contains static fields and methods; consider making it a final class instead to prevent subclassing.
InterruptedExceptionSwallowed
This catch block appears to be catching an explicitly declared InterruptedException as an Exception/Throwable and not handling the interruption separately.
InvalidBlockTag
This tag is invalid.
InvalidInlineTag
This tag is invalid.
InvalidParam
This @param tag doesn't refer to a parameter of the method.
InvalidThrows
The documented method doesn't actually throw this checked exception.
MissingDefault
The Google Java Style Guide requires that each switch statement includes a default statement group, even if it contains no code. (This requirement is lifted for any switch statement that covers all values of an enum.)
MissingSummary
A summary line is required on public/protected Javadocs.
MutableMethodReturnType
Method return type should use the immutable type (such as ImmutableList) instead of the general collection interface type (such as List)
NoFunctionalReturnType
Instead of returning a functional type, return the actual type that the returned function would return and use lambdas at use site.
NonCanonicalStaticMemberImport
Static import of member uses non-canonical name
NullableDereference
Dereference of possibly-null value
PrimitiveArrayPassedToVarargsMethod
Passing a primitive array to a varargs method is usually wrong
ProtosAsKeyOfSetOrMap
Protos should not be used as a key to a map, in a set, or in a contains method on a descendant of a collection. Protos have non deterministic ordering and proto equality is deep, which is a performance issue.
ProvidesFix
BugChecker has incorrect ProvidesFix tag, please update
QualifierWithTypeUse
Injection frameworks currently don't understand Qualifiers in TYPE_PARAMETER or TYPE_USE contexts.
RedundantOverride
This overriding method is redundant, and can be removed.
RedundantThrows
Thrown exception is a subtype of another
ReturnFromVoid
Void methods should not have a @return tag.
StaticQualifiedUsingExpression
A static variable or method should be qualified with a class name, not expression
StringEquality
String comparison using reference equality instead of value equality
SystemExitOutsideMain
Code that contains System.exit() is untestable.
TestExceptionChecker
Using @Test(expected=…) is discouraged, since the test will pass if any statement in the test method throws the expected exception
ThrowSpecificExceptions
Consider throwing more specific exceptions rather than (e.g.) RuntimeException. Throwing generic exceptions forces any users of the API that wish to handle the failure mode to catch very non-specific exceptions that convey little information.
TimeUnitMismatch
An value that appears to be represented in one unit is used where another appears to be required (e.g., seconds where nanos are needed)
TransientMisuse
Static fields are implicitly transient, so the explicit modifier is unnecessary
UnescapedEntity
Javadoc is interpreted as HTML, so HTML entities such as &, <, > must be escaped.
UnnecessaryDefaultInEnumSwitch
Switch handles all enum values: an explicit default case is unnecessary and defeats error checking for non-exhaustive switches.
UnusedException
This catch block catches an exception and re-throws another, but swallows the caught exception rather than setting it as a cause. This can make debugging harder.
Var
Non-constant variable missing @Var annotation
BooleanParameter
Use parameter comments to document ambiguous literals
ClassNamedLikeTypeParameter
This class's name looks like a Type Parameter.
ConstantField
Field name is CONSTANT_CASE, but field is not static and final
EmptySetMultibindingContributions
@Multibinds is a more efficient and declarative mechanism for ensuring that a set multibinding is present in the graph.
ExpectedExceptionRefactoring
Prefer assertThrows to ExpectedException
FieldCanBeFinal
This field is only assigned during initialization; consider making it final
FieldCanBeLocal
This field can be replaced with a local variable in the methods that use it.
FieldMissingNullable
Fields that can be null should be annotated @Nullable
ImmutableRefactoring
Refactors uses of the JSR 305 @Immutable to Error Prone's annotation
ImplementAssertionWithChaining
Prefer check(…), which usually generates more readable failure messages.
LambdaFunctionalInterface
Use Java's utility functional interfaces instead of Function<A, B> for primitive types.
MethodCanBeStatic
A private method that does not reference the enclosing instance can be static
MixedArrayDimensions
C-style array declarations should not be used
MultiVariableDeclaration
Variable declarations should declare only one variable
MultipleTopLevelClasses
Source files should not contain multiple top-level class declarations
MultipleUnaryOperatorsInMethodCall
Avoid having multiple unary operators acting on the same variable in a method call
PackageLocation
Package names should match the directory they are declared in
ParameterComment
Non-standard parameter comment; prefer /* paramName= */ arg
ParameterNotNullable
Method parameters that aren't checked for null shouldn't be annotated @Nullable
PrivateConstructorForNoninstantiableModule
Add a private constructor to modules that will not be instantiated by Dagger.
PrivateConstructorForUtilityClass
Classes which are not intended to be instantiated should be made non-instantiable with a private constructor. This includes utility classes (classes with only static members), and the main class.
RemoveUnusedImports
Unused imports
ReturnMissingNullable
Methods that can return null should be annotated @Nullable
ScopeOnModule
Scopes on modules have no function and will soon be an error.
SwitchDefault
The default case of a switch should appear at the end of the last statement group
TestExceptionRefactoring
Prefer assertThrows to @Test(expected=…)
ThrowsUncheckedException
Unchecked exceptions do not need to be declared in the method signature.
TryFailRefactoring
Prefer assertThrows to try/fail
TypeParameterNaming
Type parameters must be a single letter with an optional numeric suffix, or an UpperCamelCase name followed by the letter 'T'.
UngroupedOverloads
Constructors and methods with the same name should appear sequentially with no other code in between. Please re-order or re-name methods.
UnnecessaryBoxedAssignment
This expression can be implicitly boxed.
UnnecessaryBoxedVariable
It is unnecessary for this variable to be boxed. Use the primitive instead.
UnnecessarySetDefault
Unnecessary call to NullPointerTester#setDefault
UnnecessaryStaticImport
Using static imports for types is unnecessary
UseBinds
@Binds is a more efficient and declarative mechanism for delegating a binding.
WildcardImport
Wildcard imports, static or otherwise, should not be used