You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过反射判断Kotlin中的类及KProperty1是否为泛型?

问题解答

一、判断KProperty1是否对应泛型类型参数

可以通过检查属性返回类型的classifier是否为KTypeParameter实例来判断。泛型参数对应的类型,其classifier本质是Kotlin反射中的KTypeParameter对象,而非具体的类KClass。

示例代码:

import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.KTypeParameter

data class KeyValuePair<T : Any>(
    val key: String,
    val value: T
)

fun main() {
    val kvClass = KeyValuePair::class
    // 获取value属性
    val valueProp = kvClass.declaredMemberProperties.first { it.name == "value" }
    // 判断是否为泛型参数类型
    val isGenericType = valueProp.returnType.classifier is KTypeParameter
    println(isGenericType) // 输出 true

    // 对比key属性
    val keyProp = kvClass.declaredMemberProperties.first { it.name == "key" }
    println(keyProp.returnType.classifier is KTypeParameter) // 输出 false
}

二、判断Kotlin类是否为泛型类

直接通过KClass.typeParameters属性判断即可:该属性返回类声明的所有泛型类型参数列表,若列表不为空,则说明是泛型类。

示例代码:

fun main() {
    val isGenericClass = KeyValuePair::class.typeParameters.isNotEmpty()
    println(isGenericClass) // 输出 true

    // 对比非泛型类
    val isNonGenericClass = String::class.typeParameters.isNotEmpty()
    println(isNonGenericClass) // 输出 false
}

内容的提问来源于stack exchange,提问作者user14381362

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 20:02:38