如果仅在运行时知道属性名称,如何读取 Kotlin 数据类实例中的属性值?
问问题
34871 次
4 回答
49
这是一个从给定属性名称的类的实例中读取属性的函数(如果找不到属性,则抛出异常,但您可以更改该行为):
import kotlin.reflect.KProperty1
import kotlin.reflect.full.memberProperties
@Suppress("UNCHECKED_CAST")
fun <R> readInstanceProperty(instance: Any, propertyName: String): R {
val property = instance::class.members
// don't cast here to <Any, R>, it would succeed silently
.first { it.name == propertyName } as KProperty1<Any, *>
// force a invalid cast exception if incorrect type here
return property.get(instance) as R
}
构建.gradle.kts
dependencies {
implementation(kotlin("reflect"))
}
使用
// some data class
data class MyData(val name: String, val age: Int)
val sample = MyData("Fred", 33)
// and reading property "name" from an instance...
val name: String = readInstanceProperty(sample, "name")
// and reading property "age" placing the type on the function call...
val age = readInstanceProperty<Int>(sample, "age")
println(name) // Fred
println(age) // 33
于 2016-02-21T17:47:53.800 回答
22
您可以通过反射来做到这一点,对于数据类和普通类都是一样的。
第一个选项只是使用 Java 反射:
val name = obj.javaClass
.getMethod("getName") // to get property called `name`
.invoke(obj)
你甚至可以做一个扩展函数:
inline fun <reified T : Any> Any.getThroughReflection(propertyName: String): T? {
val getterName = "get" + propertyName.capitalize()
return try {
javaClass.getMethod(getterName).invoke(this) as? T
} catch (e: NoSuchMethodException) {
null
}
}
它称为公共吸气剂。要获取私有属性的值,您可以使用getDeclaredMethod
和修改此代码setAccessible
。这也适用于具有相应 getter 的 Java 对象(但它错过了和getter的约定)。is
has
boolean
和用法:
data class Person(val name: String, val employed: Boolean)
val p = Person("Jane", true)
val name = p.getThroughReflection<String>("name")
val employed = p.getThroughReflection<Boolean>("employed")
println("$name - $employed") // Jane - true
第二个选项涉及使用
kotlin-reflect
您应该单独添加到项目中的库,这里是它的文档。它将让您获得实际的 Kotlin 属性值,而忽略 Java getter。
您可以使用javaClass.kotlin
获取实际的 Kotlin 类令牌,然后从中获取属性:
val name = p.javaClass.kotlin.memberProperties.first { it.name == "name" }.get(p)
此解决方案仅适用于 Kotlin 类,不适用于 Java 类,但如果您需要使用 Kotlin 类,它会更加可靠:它不依赖于底层实现。
于 2016-02-20T16:14:41.990 回答
12
上面的答案对我不起作用,所以我为此创建了一个扩展函数:
@Throws(IllegalAccessException::class, ClassCastException::class)
inline fun <reified T> Any.getField(fieldName: String): T? {
this::class.memberProperties.forEach { kCallable ->
if (fieldName == kCallable.name) {
return kCallable.getter.call(this) as T?
}
}
return null
}
这是一个示例调用:
val valueNeeded: String? = yourObject.getField<String>("exampleFieldName")
还将它包含在您应用的 build.gradle 中:
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
于 2019-05-13T15:12:11.013 回答
1
我想知道是否可以以编程方式定义字段的类型。您可以通过以下方式轻松获取类型:
kCallable.returnType
但是,您仍然必须明确分配泛型类型:
getField<String>
代替
getField<kCallable.returnType>
编辑:我最终使用了以下内容:
when (prop.call(object)) {
is ObservableList<*> -> {}
is Property<*> -> {}
}
于 2020-08-01T11:22:41.680 回答