简体   繁体   English

Kotlin - 使用反射获取 static 函数

[英]Kotlin - Get static functions with reflection

I was using this piece of code to map all static functions of a Java class to stuff:我正在将这段代码用于 map Java ZA2F2ED4F8EBC2CBBD4C21 的所有 static 函数到 stuffA:

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.但我发现它只适用于 Java 代码。 It filters out companion object functions and singleton object functions.它过滤掉伴随的 object 函数和 singleton object 函数。 How can I fix it?我该如何解决?

Actually, this code works for Kotlin code, but usually Kotlin code does not have any static members.实际上,此代码适用于 Kotlin 代码,但通常 Kotlin 代码没有任何 static 成员。 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 .同样,您可以通过clazz.companionObjectInstance获取同伴的实例。

Alternatively, you can reference a companion class directly with eg: MyClass.Companion::class and then list its non-static members.或者,您可以直接使用例如MyClass.Companion::class引用配套 class,然后列出其非静态成员。

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

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