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

如何用Kotlin反射获取Room实体数据类的@ColumnInfo注解、变量及类型?

问题

我有一个同时作为Room实体的Kotlin数据类,示例代码如下:

data class Pack(
    @ColumnInfo(name = "name")
    @SerializedName("name")
    var name: String,

    @SerializedName("is_free")
    @ColumnInfo(name = "is_free")
    var isFree: Boolean,

    @SerializedName("is_new")
    @ColumnInfo(name = "is_new")
    var isNew: Boolean,
) { .. }

我想要获取所有@ColumnInfo(name)的值,即Room注解名称、对应的Kotlin变量名及其类型,期望得到如下格式的结果:name - name - String;is_free - isFree - Boolean;is_new - isNew - Boolean。请问能否通过Kotlin反射实现该需求?

回答

当然可以通过Kotlin反射实现,核心逻辑是遍历数据类的成员属性,筛选出带有@ColumnInfo注解的属性,再分别提取注解参数、属性名和属性类型。

实现代码

import androidx.room.ColumnInfo
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.findAnnotation

fun extractRoomColumnInfo() {
    // 获取Pack类的所有成员属性
    val properties = Pack::class.declaredMemberProperties
    
    // 处理每个属性并生成目标格式字符串
    val result = properties.mapNotNull { property ->
        // 查找当前属性的ColumnInfo注解,无则跳过
        val columnAnnotation = property.findAnnotation<ColumnInfo>() ?: return@mapNotNull null
        
        val columnName = columnAnnotation.name
        val varName = property.name
        // 简化类型名称,去掉包前缀
        val varType = property.returnType.toString().substringAfterLast('.')
        
        "$columnName - $varName - $varType"
    }.joinToString(";")

    println(result)
    // 输出:name - name - String;is_free - isFree - Boolean;is_new - isNew - Boolean
}

关键细节说明

  • Pack::class.declaredMemberProperties:直接获取数据类的所有成员属性,包括私有属性(如果有的话)
  • findAnnotation<ColumnInfo>():精准定位属性上的Room注解,过滤掉无该注解的属性
  • property.returnType:获取属性的类型信息,通过substringAfterLast('.')去除包名前缀,得到简洁的类型名称
  • joinToString(";"):将所有结果拼接成你需要的格式

注意事项

使用Kotlin反射需要在项目依赖中添加反射库,在build.gradle(Module级别)中添加:

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-reflect:${kotlin_version}"
}

内容的提问来源于stack exchange,提问作者Saneen K P

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:10:50