Kapt:如何阅读注释(及其参数)

Kapt: How to read annotation (and its parameters)

有 class:

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

还有一个处理器:


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()
    

    }
}

如何从 @AnotherAnnotation 读取值 "X"

将rt.jar添加到配置:

build.gradle.kts:

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

处理器:

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
    }