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/