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

Kotlin Multiplatform重命名包后访问MR资源文件夹遇空指针问题

Kotlin Multiplatform重命名包后读取MR资源报NullPointerException

问题场景

重命名项目包名后,尝试读取MR/files/locations.json文件时触发NullPointerException。

MR文件夹结构

commonMain/resources/MR/files/locations.json

现有代码实现

跨平台资源读取接口声明

expect class ResourceReader() {
    fun readResource(name: String): String
}

Android平台实际实现

actual class ResourceReader {
    actual fun readResource(name: String): String = 
        javaClass.classLoader!!.getResourceAsStream(name).use { stream ->
            InputStreamReader(stream).use { reader ->
                reader.readText()
            }
    }
}

资源调用代码

val jsonString = ResourceReader().readResource("MR/files/locations.json")

多平台资源依赖配置

插件引入

plugins {
    ...
    id("dev.icerock.mobile.multiplatform-resources")
    ...
}

SourceSets依赖配置

sourceSets {
    val commonMain by getting {
        dependencies {
            ...
            api("dev.icerock.moko:resources:0.21.1")
            ...
        }
    }
    ...
}

Buildscript配置

buildscript {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
    dependencies {
        ...
        classpath("dev.icerock.moko:resources-generator:0.17.0")
        ...
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        maven(url = "https://kotlin.bintray.com/kotlinx/")
    }
}

解决方案

1. 使用moko-resources原生API访问资源(推荐)

moko-resources会自动处理包名变更后的资源路径,无需硬编码路径:

// 直接通过生成的MR对象访问文件
val jsonString = MR.files.locations.readText()

2. 修复自定义ResourceReader的路径问题

如果必须保留自定义读取类,不要硬编码路径,改用moko-resources的FileResource对象:

// 修改expect接口
expect class ResourceReader() {
    fun readResource(resource: FileResource): String
}

// Android平台actual实现
actual class ResourceReader {
    actual fun readResource(resource: FileResource): String = 
        resource.readText()
}

// 调用方式
val jsonString = ResourceReader().readResource(MR.files.locations)

3. 统一moko-resources版本

当前resources依赖版本为0.21.1,但resources-generator版本为0.17.0,版本不匹配会导致生成的MR代码异常,需统一版本:

buildscript {
    dependencies {
        ...
        classpath("dev.icerock.moko:resources-generator:0.21.1")
        ...
    }
}

4. 清理缓存并重新构建

包名变更后残留旧编译资源可能导致问题,执行以下命令清理后重新构建:

./gradlew clean build

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:53:23