TypeToString
TypeMirror#toString shouldn't be used for comparison as it is expensive and fragile.

Severity
SUGGESTION

The problem

Type#toString shouldn’t be used for Type comparison as it is expensive and fragile.

Annotation Processors

There are a few potential options to use APIs to compare different type mirrors, depending on the requirements.

Consider if the type being inspected will always be a DeclaredType (a class or interface), or if it can also by a type variable, primitive type, or another TypeKind.

Prefer using auto-common if possible. To test a DeclaredType, use:

If you’re not sure if the TypeMirror is a class or interface, add a MoreTypes#isType check before calling isTypeOf or asTypeElement.

To test primitive types, you can use typeMirror.getKind() == TypeKind.INT.

To compare arbitrary TypeMirrors, use MoreTypes#equivalence.

If auto-common isn’t available, use javax.lang.model.util.Types and javax.lang.model.util.Elements (which are available from ProcessingEnvironment).

To compare against a generic type with specific type arguments, use getDeclaredType to construct an instantiation of a generic type to compare against:

types.isSameType(
    typeMirror,
    types.getDeclaredType(
        elements.getTypeElement("java.util.List"),
        elements.getTypeElement("java.lang.String").asType()));

Error Prone

If this code is within an Error Prone check for comparing Type(s), all of the same annotation processing APIs discussed above are available, but there are some additional options.

Suppression

Suppress false positives by adding the suppression annotation @SuppressWarnings("TypeToString") to the enclosing element.