从自定义 class 注释中获取 class 属性

Get class properties from custom class annotation

我有一个自定义 class 注释,我想使用注释的 class' 属性名称和类型生成关联的 class。是否可以收集这些信息?

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class Associated

//==============================

@Associated
data class SomeClass(
    val property1: String,
    val property2: Boolean,
    val property3: SomeEnumClass
)

//==============================

class Processor : AbstractProcessor() {
    override fun getSupportedAnnotationTypes() = setOf(
        Associated::class.java.canonicalName,
    )

    override fun process(annotations: Set<TypeElement>?, roundEnv: RoundEnvironment): Boolean {
        roundEnv.getElementsAnnotatedWith(Associated::class.java).forEach { element ->

            // QUESTION: How to get a list of properties of this element? i.e. For `SomeClass`:
            // name: "property1" of type name "String"
            // name: "property2" of type name "Boolean"
            // name: "property3" of type name "SomeEnumClass"
        }
    }
}

可以使用element.enclosedElements获取包含的元素,然后通过ElementKind.FIELD过滤:

override fun process(annotations: Set<TypeElement>?, roundEnv: RoundEnvironment): Boolean {
        roundEnv.getElementsAnnotatedWith(Associated::class.java).forEach { element ->
            element.enclosedElements.filter {
                it.kind == ElementKind.FIELD
            }.forEach { fieldElement ->
                val name = fieldElement.simpleName.toString(),
                val type = fieldElement.asType().toString()
            )
        }
    }
}