Kotlin反射无法读取成员属性值问题求助
解决Kotlin反射获取属性值时的类型不匹配异常
你的代码在通过反射遍历Person类属性并取值时抛出类型不匹配异常,错误信息显示Argument type mismatch: actual type is 'com.example.Person', but 'CapturedType(out com.example.Person)' was expected。
问题原因
person::class.memberProperties返回的是Collection<KProperty1<out Person, *>>,其中out Person是协变类型,意味着该属性的接收者可以是Person的任意子类型。直接传入确切的Person实例时,Kotlin的类型检查会因为协变限制判定类型不匹配。
解决方案1:强制转换属性类型(带警告抑制)
通过将属性强制转换为KProperty1<Person, *>,明确指定接收者类型为Person,即可正常调用get方法:
package com.example import kotlin.reflect.full.memberProperties import kotlin.reflect.KProperty1 fun main() { val person = Person("Alice", 29) person::class.memberProperties.forEach { @Suppress("UNCHECKED_CAST") val property = it as KProperty1<Person, *> println("${property.name} = ${property.get(person)}") } } data class Person(val name: String, val age: Int)
解决方案2:将实例转为Any类型传入
由于所有Kotlin类都继承自Any,将person转为Any类型后,符合KProperty1<out Person, *>.get方法的参数要求:
package com.example import kotlin.reflect.full.memberProperties fun main() { val person = Person("Alice", 29) person::class.memberProperties.forEach { println("${it.name} = ${it.get(person as Any)}") } } data class Person(val name: String, val age: Int)
两种方案都能正常输出:
name = Alice age = 29
内容的提问来源于stack exchange,提问作者HonzaJazz
相关产品推荐
相关产品推荐

