如何为私有字段构建Kproperty



有人能帮我回答问题吗?

我编写以下函数,该函数接收KProperty1<T、 *>作为参数:

fun <T> printProperty(instance: T, prop: KProperty1<T, *>) {
println("prop : ${prop.get(instance)}")
}

我还定义了一个Person类:

class Person(val name: String, var age: Int, private var address: String = "") {
// empty body
}

但是当我写测试代码时,地址属性的编译失败了,

printProperty(person, Person::name) // Compile success
printProperty(person, Person::age) // Compile success
printProperty(person, Person::address) // Compile failed!!!

虽然我知道这是因为地址字段是私有的,不能像Person::address那样访问。但是,有没有一种方法可以为私有字段构造Kproperty,使其也可以被函数使用?

使用Kotlin反射,您可以定义printProperty函数,使每个属性在访问之前都可以访问:

import kotlin.reflect.KCallable
import kotlin.reflect.jvm.isAccessible
fun <T> printProperty(instance: T, prop: KCallable<T>) {
prop.isAccessible = true
println("prop : ${prop.call(instance)}")
}

由于Person::address仍然是私有的,您必须以不同的方式访问它:

printProperty(person, Person::name) // public
printProperty(person, Person::age) // public
printProperty(person, Person::class.members.first { it.name == "address" }) // private

最新更新