Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用kotlin reflect查找数据类的数据类型';s属性_Kotlin_Kotlin Reflect - Fatal编程技术网

使用kotlin reflect查找数据类的数据类型';s属性

使用kotlin reflect查找数据类的数据类型';s属性,kotlin,kotlin-reflect,Kotlin,Kotlin Reflect,给定一个简单的数据类,如: 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查找属性的数据类型?我通过以

给定一个简单的数据类,如:

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()
}

首先,您可以使用一些库将JSON解析为实际类型。杰克逊有很好的科特林支持。 如果不想使用库,要确定参数的类型,可以使用以下代码段:

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<*>}")
        }
    }
}

谢谢你的回答。我设法得到了你们建议的结果,但我想不出一个方法来达到这个结果。有什么想法吗?例如:“val clazz=prop.returnType.classifier作为KClass;val result=value作为clazz”?在这种情况下,
value
是Any类型。好的,我可以让
clazz很长
工作,所以求助于
clazz.simpleName==“Long”
。虽然不理想,但目前仍有效。谢谢你到底想对这些信息做什么?根据我发布的“castToLong”函数,我正在寻找一种方法来创建类似“inline fun castTo(value:Any,type:T):T”或其变体的内容,这样我就可以避免创建“castToLong”、“castToLong”等。如果我很了解你,您希望解析JSON数据,所以可能不希望将字符串强制转换为其他类型。您需要提供转换器,例如。G
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