mercredi 28 octobre 2020

Local function reflection Kotlin

I understood how to get declared functions in a class.

Example:

@Target(AnnotationTarget.FUNCTION)
annotation class Foo (val name: String)

class Bar {
    fun main() {
        val declaredMethods = this::class.java.declaredMethods

        declaredMethods.filter {
            it.isAnnotationPresent(Foo::class.java)
        }.forEach {
            it.invoke(this)
        }
    }

    @Foo("foo")
    fun baz() {
        println("foo")
    }
}

Now, I want to retrieve local functions that have an annotation.

Example:

@Target(AnnotationTarget.FUNCTION)
annotation class Foo (val name: String)

@Foo("foo")
fun baz() {
    println("foo")
}

Thank you in advance, Bye

EDIT FOR Konstantin Raspopov: Thanks for your answer, sadly my functions are in different files and I don't know the name of the classes.





Aucun commentaire:

Enregistrer un commentaire