如何通过Kotlin DSL从build.gradle.kts内定义的任务调用带参数的默认Gradle run任务?
run Task from a Custom Task in build.gradle.kts Hey there! I see you've already got a custom task calling the default run task in your build.gradle.kts, and now you need to pass arguments to it—let's fix that up right away. There are two main types of arguments you might want to pass: program arguments (for your application's main method) and JVM arguments, so I'll cover both scenarios with practical examples.
1. Passing Program Arguments (Main Method Args)
The default run task exposes an args property that accepts a list of strings to pass to your application's entry point. You can set this property directly from your custom task, either hardcoding values or pulling them from command-line properties for flexibility.
Example: Hardcoded Arguments
tasks.register("customRun") { // Ensure the default run task executes after our configuration dependsOn(tasks.run) // Configure the run task's arguments before it executes doFirst { // Pass arguments like you would with `./gradlew run --args="--input data.txt -v"` tasks.run.args = listOf("--input", "data.txt", "-v") } }
Example: Accept Arguments from Command Line
If you want to pass dynamic arguments when invoking the custom task, use Gradle project properties:
tasks.register("customRunDynamic") { dependsOn(tasks.run) doFirst { // Pull arguments from the command line (e.g., ./gradlew customRunDynamic -PappArgs="--input,data.txt,-v") val appArgs = project.properties["appArgs"]?.toString()?.split(",") ?: emptyList() tasks.run.args = appArgs } }
2. Passing JVM Arguments
If you need to pass JVM-specific flags (like heap size or system properties), use the run task's jvmArgs property instead.
Example: Hardcoded JVM Arguments
tasks.register("customRunWithJvm") { dependsOn(tasks.run) doFirst { // Set JVM flags (e.g., max heap size and a system property) tasks.run.jvmArgs = listOf("-Xmx512m", "-Dconfig.path=./config.yml") } }
Example: Dynamic JVM Arguments from Command Line
tasks.register("customRunWithDynamicJvm") { dependsOn(tasks.run) doFirst { // Pull JVM args from command line (e.g., ./gradlew customRunWithDynamicJvm -PjvmFlags="-Xmx1g,-Denv=dev") val jvmFlags = project.properties["jvmFlags"]?.toString()?.split(",") ?: emptyList() tasks.run.jvmArgs = jvmFlags } }
3. Append Arguments Instead of Overwriting
If you don't want to replace any existing arguments configured for the run task, use addAll() instead of setting the list directly:
tasks.register("customRunWithExtraArgs") { dependsOn(tasks.run) doFirst { // Add extra program arguments without replacing existing ones tasks.run.args.addAll(listOf("--verbose", "--log-file=app.log")) // Same logic applies to JVM arguments tasks.run.jvmArgs.addAll(listOf("-XX:+UseG1GC")) } }
Testing It Out
Just run your custom task like you would any Gradle task:
./gradlew customRun
The default run task will execute with all the arguments you've configured from your custom task.
内容的提问来源于stack exchange,提问作者Erdem Tuna

