我有一个方法引用(由kotlin.reflect.KFunction0接口表示).我想要做的是获取方法引用的receiver对象.

例如:

data class MyClass(val name: String)

val john = MyClass("John")
val methodReference = john::toString

methodReference.receiver // doesn't work!

methodReference中的第receiver个是对象john.如果我查看IntelliJ调试器,methodReference有一个receiver字段,它实际上指向john.但我找不到在我的代码中实际访问它的方法.

有什么办法可以解决这个问题吗?

推荐答案

假设这是kotlin/jvm,您看到的receiver字段是在CallableReference中声明的受保护字段.您可以使用Java反射来实现这一点.

val f = someINstance::foo
val receiverField = CallableReference::class.java.getDeclaredField("receiver")
receiverField.isAccessible = true
println(receiverField.get(f))

我不确定这个字段是否为guaranteed而被称为receiver,或者它是否会在future 的版本中存在.我找不到任何关于这方面的官方文件.

还要注意的是,并不是每KFunction0个都有接收器.在这种情况下,receiverField.get(f)将返回CallableReference.NO_RECEIVER.

Kotlin相关问答推荐

Kotlin—从列表中枚举属性计算不同值的数量

Kotlin异步不并行运行任务

在Kotlin中,我是否可以访问已知的WHEN子句值?

Kotlin SAM/功能接口抛出 AbstractMethodError

Jetpack compose 可滚动表格

Kotlin - 创建指定长度的随机整数的 ArrayList?

如何在 Android 的 Fragment 中使用 setUserVisibleHint

如何使用 Android CameraX 自动对焦

找不到 androidsdk.modules

包括登录Elvis operator?

取消信号上的kotlin流量采集

使用 Paging 3 时保存并保留 LazyColumn 滚动位置

Kotlin - 来自 KType 的 KClass<*>

有没有办法在数据类构建时转换属性的值?

Kotlin JVM 和 Kotlin Native 有什么区别?

如何解决:将Java类转换为Kotlin后出现error: cannot find symbol class ...?

Android Jetpack导航,另一个主机片段中的主机片段

如何序列化/反序列化Kotlin密封类?

IllegalStateException:function = , count = 3, index = 3

在 Android 12 (SDK 31) 中获取 android.app.ForegroundServiceStartNotAllowedException