mardi 27 mars 2018

How to declare a reflection-iterable set of functions in Kotlin?

I want to declare a set of Kotlin functions that are not member functions of a class (i.e. „static“ functions without reference to a class instance). They have to be declared in a way so that I can iterate over them using reflection during runtime.

My first try was to write a file Commands.kt like this:

fun a(): Int = 42
fun b(): Int = 23

However, I did not find a way to iterate over the functions in this file. I know that for Java compatibility, a class CommandsKt will be generated that contains those functions as static methods. However, I seem not to be able to reference that class in Kotlin, neither did I find a way to iterate over all entities of a Kotlin file via reflection.

My second try was to use an object:

object Commands {
    fun a(): Int = 42
    fun b(): Int = 23
}

I can iterate over the member functions via Commands::class.declaredMemberFunctions now. However, those functions would still be member functions, not „static“ (in Java speak) functions (right?).

So how would I declare those functions so that they are both static and iterable via reflection?





Aucun commentaire:

Enregistrer un commentaire