Search code examples
javaandroidkotlinannotation-processing

AnnotationProcessor in mixed java/kotlin Android project does not process kotlin class


In an Android project (native with mixed java / kotlin) we use a simple annotation processor to generate a class in our build process. That generated class contains all Activity classes in the project that have been annotated with a specific project internal annotation, we use this to initialize some specific hardware on android devices.

That annotation processor works fine, we now ran into an issue with a single Activity class not getting compiled into that generated class. I realize that this Activity is the second one implemented in kotlin and the first kotlin based Activity with the annotation in question.

So I dove into the annotation processor, checked the set of annotated files we get from the RoundEnvironment and indeed, the Activity class is already missing in the set our processor operates on.

So my question is:

  • Why is that kotlin based Activity class not included in the environment?
  • Or what do I have to do to get it included?

Here is the relevant code if the annotation processor:

// [...]
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
// [...]

@SupportedAnnotationTypes(EnableScannerTypesAnnotationProcessor.ENABLE_SCANNER_ANNOTATION)
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SuppressWarnings("PMD.ConsecutiveLiteralAppends")
public class EnableScannerTypesAnnotationProcessor
    extends AbstractProcessor {

    // [...]

    @Override
    public synchronized void init(ProcessingEnvironment processingEnvironment) {
        super.init(processingEnvironment);
        // [...]
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    
        for (TypeElement annotation : annotations) {
            if (annotation.getQualifiedName().contentEquals(ENABLE_SCANNER_ANNOTATION)) {
                final Set<? extends Element> annotatedTypes = roundEnv.getElementsAnnotatedWith(annotation);
                // the processor now operates on the set `annotatedTypes`
                // [...] 

Solution

  • We ended up reimplementing the annotation processor based on KSP instead of KAPT. That way it indeed does see the kotlin based classes as well.

    The reimplementation was pretty straight forward. Though I would have wished for a better documentation for KSP.