给出一个简单的数据类,比如:
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,它返回一个KType。我想不出一种方法来检查KType是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()
}发布于 2019-02-01 19:19:15
首先,您可以使用一些库将JSON解析为实际的类型。杰克逊有很好的Kotlin支持。如果你不想使用库来确定参数的类型,你可以使用下面的代码片段:
import java.time.OffsetDateTime
import kotlin.reflect.KClass
import kotlin.reflect.full.declaredMemberProperties
data class UpdateTaskDto(
val taskListId: Long,
val name: String,
val description: String? = null,
val parentTaskId: Long? = null,
val previousTaskId: Long? = null,
val dateFrom: OffsetDateTime? = null,
val dateTo: OffsetDateTime? = null,
val dateOnlyMode: Boolean? = false
) {
fun test() {
this::class.declaredMemberProperties.forEach { type ->
println("${type.name} ${type.returnType.classifier as KClass<*>}")
}
}
}作为调用test方法的结果,我得到:
dateFrom class java.time.OffsetDateTime
dateOnlyMode class kotlin.Boolean
dateTo class java.time.OffsetDateTime
description class kotlin.String
name class kotlin.String
parentTaskId class kotlin.Long
previousTaskId class kotlin.Long
taskListId class kotlin.Longhttps://stackoverflow.com/questions/54476529
复制相似问题