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

Android多模块项目中Gradle任务运行主类报错:找不到main源集

问题原因

你的offlinedb是Android Library模块,使用Android Gradle插件管理,而非普通的Java/Kotlin JVM插件。普通JVM插件的sourceSets直接挂在project对象下,但Android插件的源集要通过android.sourceSets访问,所以直接调用project(":offlinedb").sourceSets["main"]会找不到对应源集。

至于改用android.sourceSets["main"]后找不到主类,核心原因是Android Library默认编译产物是供Android运行的字节码,不会主动打包可独立运行的JVM类(带main函数的类),或者你指定的主类路径存在错误。

解决方案

方案1:适配Android Library模块的任务配置

如果不想调整模块结构,可按以下方式修改runCodeGenerator任务:

情况1:任务配置在offlinedb模块的build.gradle.kts中

tasks.register<JavaExec>("runCodeGenerator") {
    group = "code generation"
    description = "Runs the code generator in the offlinedb module"

    // 先确保Kotlin代码编译完成
    dependsOn(tasks.named("compileDebugKotlin"))

    // 指定Android模块编译后的类文件目录,包含Kotlin编译产物
    val androidClassDir = layout.buildDirectory.dir("intermediates/javac/debug/classes")
    val kotlinClassDir = layout.buildDirectory.dir("tmp/kotlin-classes/debug")
    classpath(files(androidClassDir, kotlinClassDir))

    // Kotlin文件的main函数编译后,类名为「原文件名+Kt」,注意路径要和包名对应
    mainClass.set("com.framework.offlinedb.generator.MainKt")

    // 传递自定义参数(按需修改)
    args = listOf("arg1", "arg2")
}

情况2:任务配置在根项目的build.gradle.kts中

tasks.register<JavaExec>("runCodeGenerator") {
    group = "code generation"
    description = "Runs the code generator in the offlinedb module"

    val offlineDb = project(":offlinedb")
    // 依赖offlinedb模块的编译任务
    dependsOn(offlineDb.tasks.named("compileDebugKotlin"))

    // 引用offlinedb模块的编译输出目录
    val androidClassDir = offlineDb.layout.buildDirectory.dir("intermediates/javac/debug/classes")
    val kotlinClassDir = offlineDb.layout.buildDirectory.dir("tmp/kotlin-classes/debug")
    classpath(files(androidClassDir, kotlinClassDir))

    mainClass.set("com.framework.offlinedb.generator.MainKt")
    args = listOf("arg1", "arg2")
}

方案2:将代码生成器迁移到独立JVM模块(更规范)

Android Library模块本身是为Android运行环境设计的,不适合存放可独立运行的JVM程序,更合理的做法是:

  1. 创建新的Kotlin JVM模块(例如命名code-generator),将com.framework.offlinedb.generator下的代码移到该模块。
  2. 在该模块的build.gradle.kts中配置基础插件:
plugins {
    kotlin("jvm") version "你的Kotlin版本号"
}

repositories {
    mavenCentral()
}

dependencies {
    // 添加代码生成所需的依赖(如JPA、模板引擎等)
}
  1. 在该模块中配置runCodeGenerator任务:
tasks.register<JavaExec>("runCodeGenerator") {
    group = "code generation"
    description = "Runs the code generator"

    classpath = sourceSets["main"].runtimeClasspath
    mainClass.set("com.framework.offlinedb.generator.MainKt")
    args = listOf("arg1", "arg2")
}

排查主类缺失的问题

如果仍提示找不到主类,可手动验证:

  • 打开offlinedb/build/tmp/kotlin-classes/debug/com/framework/offlinedb/generator/目录,确认是否存在MainKt.class文件。
  • 如果文件不存在,检查该Kotlin文件是否引用了Android SDK类(如Context),如果是,需将代码调整为纯JVM代码,或者在Android模块的sourceSets中明确包含该文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:52:42