Reputation: 2416
I am trying to build a custom Gradle Task to perform some app maintenance operations. I would like to pass argument(s) to the task to control operations. To illustrate my dilemma, consider to following two trivial custom task classes:
// Custom task with no arguments
public class HelloClassA extends DefaultTask {
@TaskAction
public void printHello()
{
println "Hello, World!"
}
}
// Custom task with one argument
public class HelloClassB extends DefaultTask {
@TaskAction
public void printMsg(String msg)
{
println msg
}
}
They are identical except that "A" prints a hard-coded string while "B" accepts a string as an argument.
Class A is used in the following task:
task helloA(type:HelloClassA) { }
and is invoked by, e.g.,
gradlew.bat helloA
It works fine and prints "Hello, World!" to the Build window. However, I can't figure out the syntax is for a task to invoke Class B.
How do I do that? (or am I just way off base trying to do it this way?)
Some rather Strange Things I've noticed...
Upvotes: 1
Views: 2317
Reputation: 2416
You can pass an argument(s) directly to a method without using properties. Here's how:
apply plugin: 'com.android.application'
import javax.inject.Inject
abstract class CustomTask extends DefaultTask {
@Inject
CustomTask(String message,int number) {
println "Processing \""+message+"\", "+number // process args
}
}
Create task 'mytask' as follows in the android section appending the arguments (which must agree in count and format with the task definitions):
tasks.register( 'mytask', CustomTask, 'Hello, World!', 123 )
Execute 'mytask' by
gradlew.bat mytask
which produces the output
Processing "Hello, World!", 123
Upvotes: 1
Reputation: 9073
You can't directly pass it as an argument to the method. But, if you wish there is a way using @Input
annotation.
Following is the example for you use case:
abstract class HelloClassB extends DefaultTask {
@Input
abstract Property<String> getMsg()//this is an abstract method to get values
@TaskAction
def printMsg() {
println msg.get() // here we get the value set from task.register
}
}
// printB is the task name
tasks.register('printB',HelloClassB) {
msg = 'Hello B' // here we set the Input value
}
Now in your terminal run: gradlew -q printB
If you want to read more about this then please have a look here: https://docs.gradle.org/current/userguide/custom_tasks.html
Upvotes: 1