4

I am trying to write a simple Android lint check, which make sure you use a specific nullability annotation. But for some reason, I am not able to get the fully qualified name of the annotation.

Here's the test case:

val input = """
    package foo;

    import org.jetbrains.annotations.NotNull;

    public class Bar {
        @NotNull String text;

        Bar(@NotNull String text) {
            this.text = text;
        }
    }
""".trimIndent()

lint().files(java(input))
    .issues(NullAnnotationDetector.ISSUE)
    .run()
    // expect and all the info

Here's the logic in the detector:

class NullAnnotationDetector: Detector(), SourceCodeScanner {

    // companion object with the Issue itself

    private lateinit var uastHandler: UElementHandler

    override fun getApplicableUastTypes(): List<Class<out UElement>>? =
        listOf(UAnnotation::class.java)

    override fun createUastHandler(context: JavaContext): UElementHandler? {
        uastHandler = NullHandler(context)
        return uastHandler
    }

    private class NullHandler(val context: JavaContext) : UElementHandler() {
        override fun visitAnnotation(node: UAnnotation) {
            val x = node.qualifiedName  // for some reason this is just "NotNull"

            // context.report and all those kind of stuff
        }
    }
}

And the thing is, if I turn the input into kotlin, node.qualifiedName returns the fully qualified name (org.jetbrains.annotations.NotNull). How can I get the same result with java()?

Louis Tsai
  • 1,587
  • 3
  • 20
  • 33

1 Answers1

1

I replaced

node.qualifiedName

with

node.javaPsi?.qualifiedName

and in my tests I had to add the full definition of the class that I was testing against, in your case would be something like:

   lint()
       .files(
          notNullClass(),
          java( """
             package foo;

             import org.jetbrains.annotations.NotNull;

             public class Bar {
                @NotNull String text;

                Bar(@NotNull String text) {
                   this.text = text;
                }
             }
             """.trimIndent()
             )
          )
       .run()
       .expectErrorCount(1)

with notNullClass() defined as:

companion object {

        fun notNullClass(): TestFile = java(
            "src/org/jetbrains/annotations/NotNull.java",
            """

package org.jetbrains.annotations;

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE})
public @interface NotNull {

  String value() default "";

  Class<? extends Exception> exception() default Exception.class;
}


                """.trimIndent()
        )
    }
Sara
  • 1,844
  • 22
  • 18