Search code examples
kotlinreflectionstatic-methodscompanion-object

Kotlin - Get static functions with reflection


I was using this piece of code to map all static functions of a Java class to stuff:

fun staticsFromClass(clazz: Class<*>): List<Something> = clazz.methods
        .filter { method -> Modifier.isStatic(method.modifiers) }
        .map { method ->
           //something
        }

but I found out it only works on Java code. It filters out companion object functions and singleton object functions. How can I fix it?


Solution

  • Actually, this code works with Kotlin classes, but usually Kotlin does not have any static members. You can acquire companion members with the following code:

    fun companionMembersFromClass(clazz: KClass<*>): List<Something> {
        val members = clazz.companionObject?.members ?: emptyList()
        ...
    }
    

    Similarly, you can acquire the instance of the companion with: clazz.companionObjectInstance.

    Alternatively, you can reference a companion class directly with e.g.: MyClass.Companion::class and then list its non-static members.