Reputation: 3952
Given a simple data class like:
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
)
Is there any way I can use kotlin-reflect
to find the data type of the properties? I got all the properties via:
val allFields = this::class.declaredMemberProperties.map {
it.name to it
}.toMap()
I only got as far as allFields["number"].returnType
which returns a KType
. I couldn't figure out a way to check if a KType
is Int
or Long
.
I am trying to avoid the code I currently use to cast the incoming JSON numeric data to appropriate data type:
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()
}
Upvotes: 3
Views: 2539
Reputation: 170
First, you can use some library to parse JSON to actual types. Jackson has good Kotlin support. If you don't want to use library, to determine type of parameter you can use this snippet:
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<*>}")
}
}
}
As a result of calling test method, I got:
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.Long
Upvotes: 2