I'm looking for a way to detect if a class is inherited from another class/interface in annotation processor. Since the annotation processor runs on the source code not runtime, there's no way to use reflation API, the only method I found is:
public class MyProcessor extends AbstractProcessor {
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
// Simple test
processingEnv.getTypeUtils().isAssignable(
processingEnv.getElementUtils().getTypeElement("java.util.List").asType(),
processingEnv.getElementUtils().getTypeElement("java.util.Collection").asType()
);
}
}
But this method always returns false even though that List implements Collection. Any idea?
processingEnv.getElementUtils().getTypeElement("java.util.List")return a sensible type?List.class.getCanonicalName()andCollection.class.getCanonicalName()instead of"java.util.List"and"java.util.Collection"?List<E>is assignable to the genericCollection<E>, which is false. In your case, I assume you want to test the raw types—seeTypes#erasure(TypeMirror).