给定一个简单的数据类,例如:
data class TestSimple(
val country: String,
var city: String? = null,
var number: Int? = null,
var code: Long? = null,
var amount: Float? = null,
var balance: Double? = null
)
有什么方法可以kotlin-reflect
用来查找属性的数据类型吗?我通过以下方式获得了所有属性:
val allFields = this::class.declaredMemberProperties.map {
it.name to it
}.toMap()
我只知道allFields["number"].returnType
返回 a KType
。我想不出一种方法来检查 aKType
是Int
还是Long
.
我试图避免我目前用来将传入的 JSON 数字数据转换为适当的数据类型的代码:
fun castToLong(value: Any): Long {
val number = try {
value as Number
} catch (e: Exception) {
throw Exception("Failed to cast $value to a Number")
}
return number.toLong()
}