在JavaExec gradle任务中使用Android模块运行时类路径



我有一个Android模块,它包含一个Gradle JavaExec任务。在运行JavaExec任务时,我希望它使用模块的类路径。JavaExec任务执行Kotlin主函数,该函数使用一些第三方库(kotlinpoeter(。但是在运行Gradle任务时,由于类路径中没有包含kotlinpoeter库,我得到了一个java.lang.ClassNotFoundException

我在StackOverflow中发现了类似的问题,并尝试了myTaskclasspath参数的许多变体,但都不起作用。

这是build.gradle文件:

plugins {
id 'com.android.library'
id 'kotlin-android'
}
apply plugin: 'kotlinx-serialization'
android {
compileSdkVersion 30    
defaultConfig {
...
}
buildTypes {
...
}
compileOptions {
...
}
kotlinOptions {
jvmTarget = '1.8'
}
}
task myTask(type: JavaExec) {
classpath += (files('build/tmp/kotlin-classes/debug', "${android.sdkDirectory}/tools/lib/kotlin-stdlib-1.1.3-2.jar", getBuildDir().toString() + "/intermediates/classes/debug"))
main = 'com.foo.app.home.parser.MainKt'
}
tasks.named('build') { dependsOn('configGeneratorTask') }
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "androidx.core:core-ktx:$androidx_core_ktx"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-core:$kotlinx_serialization_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:$kotlinx_serialization_version"
implementation 'com.squareup:kotlinpoet:1.10.2'
}

您可以从每个变体中获取类路径。这应该会奏效:

afterEvaluate { // needed to make sure all android setup is available
task myTask(type: JavaExec) {
// you probably don't even need to set all these paths manually anymore
classpath += files(
'build/tmp/kotlin-classes/debug',
"${android.sdkDirectory}/tools/lib/kotlin-stdlib-1.1.3-2.jar",
getBuildDir().toString() + "/intermediates/classes/debug"
)
android.applicationVariants.each { variant -> // or libraryVariants
// add each variant's compiler classpath onto this classpath
classpath += variant.javaCompileProvider.get().classpath
}
// uncomment the line below if you need the android.jar etc
// classpath += files(android.bootClasspath) 
// setting main directly is now deprecated. Set it like this:
mainClass.set('com.foo.app.home.parser.MainKt') 
}
}

另请参阅此处的答案:https://stackoverflow.com/a/37268008/3968618