mardi 11 juillet 2023

How to find the list of extension functions of a Kotlin class and its usages using reflection? [duplicate]

I have this code so far but none of the methods return the myExtensionMethod function as expected:

import kotlin.reflect.full.declaredFunctions
import kotlin.reflect.full.declaredMemberExtensionFunctions
import kotlin.reflect.full.declaredMemberExtensionProperties
import kotlin.reflect.full.declaredMemberFunctions
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.declaredMembers

fun main() {
    println(MyEntity::class.declaredFunctions)
    println(MyEntity::class.declaredMembers)
    println(MyEntity::class.declaredMemberProperties)
    println(MyEntity::class.declaredMemberFunctions)
    println(MyEntity::class.declaredMemberExtensionProperties)
    println(MyEntity::class.declaredMemberExtensionFunctions)
}

class MyEntity(
    var id: String,
)

fun MyEntity.myExtensionMethod() {
    println("Extension")
}

This is the output:

[]
[var MyEntity.id: kotlin.String]
[var MyEntity.id: kotlin.String]
[]
[]
[]

How do I retrieve myExtensionMethod via reflection? I am trying to find all callers of this method up until the controller layer, recursively and build a graph/tree data structure.

Docs - https://kotlinlang.org/docs/extensions.html





Aucun commentaire:

Enregistrer un commentaire