gpt4 book ai didi

reflection - 我可以使用kotlin.reflect获得字段的值吗

转载 作者:行者123 更新时间:2023-12-02 13:24:18 24 4
gpt4 key购买 nike

class A{
private var p:MyObj? = null
}

看来 A::p 无法获得p,
或者我只能通过Java获得它?

我的Kotlin版本是
ext.kotlin_version = '1.1.4-2'

最佳答案

您无法获得它,因为当属性为private时,您是在该类之外进行的。您可以在此处选择以下几种方式:

  • 创建一个返回this::p(fun func(): KProperty0<MyObj?> = this::p)
  • 的函数
  • 将该属性设为public
  • 使用反射。这可能是最慢,性能最差且耦合非常紧密的选项。仅当您不能使用其他人时才使用它。您可以像这样使用Kotlin的反射:A::class.memberProperties.find { it.name == "p" } as KProperty1<A, MyObj?>
  • 关于reflection - 我可以使用kotlin.reflect获得字段的值吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46155190/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com