Get class properties from custom class annotation

Viewed 106

I have a custom class annotation, I want to generate an associated class using the annotated class' properties names and types. Is it possible to collect these information?

@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"
        }
    }
}
1 Answers

One can use element.enclosedElements to get the enclosed elements, then filter by 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()
            )
        }
    }
}
Related