Type#toString shouldn’t be used for Type comparison as it is expensive and
fragile.
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:
MoreTypes.isTypeOf - isTypeOf(Foo.class, typeMirror)MoreTypes#asTypeElement -
asTypeElement(typeMirror).getQualifiedName().contentEquals(expectedName)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).
Types#isSameType - types.isSameType(typeMirror,
elements.getTypeElement(expectedTypeName).asType())Types#asElement -
Objects.equals(types.asElement(typeMirror),
elements.getTypeElement(expectedTypeName))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()));
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.
Types can be looked up with VisitorState:
ASTHelpers.isSameType(type, visitorState.getTypeFromString("com.package.SomeObject"), state)
Some types from java.base are available as cached instances in javac’s
symbol table:
ASTHelpers.isSameType(type, state.getSymtab().objectType, state)
Suppress false positives by adding the suppression annotation @SuppressWarnings("TypeToString") to the enclosing element.