Kotlin annotation processor traverse to deep class

Hi, Currently I’m working on annotation processor. I need to read data class properties deeply and return it’s name and type

So, I have class like this:

@Test("req1")
@params
data class SomeParameter(
    val id: Int,
    val name: String,
    val dealPackage: List<Package>
)

data class Package (
    val id: Int,
    val name: String
)

The annotation having:

@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.CLASS)

So I guess I can’t use kotlin reflection to read class properties. So I’ll use kotlin metadata to read the class properties in compile time.

To read metadata of the element, I’m using kotlinpoet-metadata library.

doing like this in process method:

    val metadata = (element as TypeElement).toImmutableKmClass()
    
    metadata.constructors[0].valueParameters.forEach {
        val name = it.name
        val type = it.type
        val classifier = type?.classifier
    }

So far, I can get the The SomeParameter data class properties using classifier. The classifier will return Class(name=kotlin/collections/List) look like (string?) for each data class constructor. How can I traverse to each classifier so I can get into Package to get all it’s constructor name and type?

1 Like

Found it!

You can use:

   metadata.constructors[0].valueParameters.forEach {
        val name = it.name
        val type = it.type
        val classifier = type?.classifier

        when (val classifier = it.type?.classifier) {
             is KmClassifier.Class -> {
                 val elementPackage = classifier.name.replace("/", ".")
                 
                 // This what I looking for!! will return element based on class full name definition
                 val childElement = processingEnv.elementUtils.getTypeElement(elementPackage)
             }
         }
    }
1 Like