简体   繁体   English

局部函数反射 Kotlin

[英]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.编辑康斯坦丁拉斯波波夫:感谢您的回答,遗憾的是我的函数在不同的文件中,我不知道类的名称。

Supposing that your code is located in file Hello.kt , you can do it like this:假设您的代码位于文件Hello.kt ,您可以这样做:

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

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

fun main() {
    val clazz = Class.forName("HelloKt")
    val declaredMethods = clazz.declaredMethods

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM