Kapt: How to read annotation (and its parameters)

167 views Asked by At

Having a class:

@MarkerForKapt
@AnotherAnnotation(withParameter = "X")
class MyClass

And a processor:


class MyProcessor : AbstractProcessor() {

    override fun getSupportedAnnotationTypes() = setOf(MarkerForKapt::class.qualifiedName)

    override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
  
        val element = roundEnv.getElementsAnnotatedWith(MarkerForKapt::class.java).single()
    

    }
}

How to read value "X" from @AnotherAnnotation?

1

There are 1 answers

0
Max Farsikov On BEST ANSWER

Add rt.jar to configuration:

build.gradle.kts:

    implementation(files("${System.getProperty("java.home")}/../lib/tools.jar"))

Processor:

import com.sun.tools.javac.code.Symbol


    override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
  
        val element = roundEnv.getElementsAnnotatedWith(MarkerForKapt::class.java).single()
    

        element as Symbol.ClassSymbol

        val annotation: AnotherAnnotation? = element.getAnnotation(AnotherAnnotation::class.java)

        val theX = annotation?.withParameter
    }