以反射方式引用重载的顶级 Kotlin 函数

Referencing overloaded top-level Kotlin functions reflectively

简而言之,如何在 Kotlin 中反射性地引用/迭代重载的顶级函数,例如 kotlin.io.println


鉴于以下情况:

object Bar {
    fun foo(x: Int) = Unit
    fun foo(x: Byte) = Unit
    fun foo(x: Float) = Unit
}

我可以通过以下方式迭代 foo 的各种重载:

fun main() {
    Bar::class.memberFunctions
        .filter { kFunction -> kFunction.name == "foo" }
        .forEach { kFunction -> println(kFunction) }
}

产生:

fun com.example.Bar.foo(kotlin.Byte): kotlin.Unit
fun com.example.Bar.foo(kotlin.Float): kotlin.Unit
fun com.example.Bar.foo(kotlin.Int): kotlin.Unit

但是,如果 foo 的各种重载定义在顶层(在 class 或对象定义之外) 例如:

fun foo(x: Int) = Unit
fun foo(x: Byte) = Unit
fun foo(x: Float) = Unit

然后似乎没有办法引用它们。

我尝试在我的示例中使用顶级函数(例如main)来访问合成class:

::main::class.memberFunctions
    .filter { kFunction -> kFunction.name == "foo" }
    .forEach { kFunction -> println(kFunction) }

但它呕吐的事实是它是合成的:

Exception in thread "main" java.lang.UnsupportedOperationException: This class is an internal synthetic class generated by the Kotlin compiler, such as an anonymous class for a lambda, a SAM wrapper, a callable reference, etc. It's not a Kotlin class or interface, so the reflection library has no idea what declarations does it have. Please use Java reflection to inspect this class.

如何在 Kotlin 中引用顶级重载函数?

更具体地说,在其他包/模块中定义的顶级重载函数,例如 kotlin.io.println?

根据定义,顶级函数没有声明 class。

::println.javaClass.declaringClass //will return null

所以您没有 class 可以使用反射,因此,您无法枚举包的顶级成员。(Some magic can be done though, if you are willing to trade your soul)

您可以引用不明确的顶级函数的唯一方法是像这样帮助编译器解决歧义:

val functionReference: (Int)->Unit = :foo

然后你可以调用 functionReference()