簡體   English   中英

引用重載的頂層 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 或 object 定義之外),例如:

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

然后似乎沒有辦法引用它們。

我嘗試在我的示例中使用頂級 function(例如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 來使用反射,因此,你不能枚舉 package 的頂級成員。(如果你願意交易你的靈魂,可以做一些魔法

引用模棱兩可的頂級函數的唯一方法是幫助編譯器解決歧義,如下所示:

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

然后你可以調用 functionReference()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM