I have a custom plugin implementation. I need to pass task properties prop1 and prop2 into task class exampleClass (extending DefaultClass) with gradle command.
gradle -Pprop1={val} -Pprop2={val2} exampleTask
Class exampleClass, defined as Java class, is declared in build.gradle as
My question: How can I pass those -P parameters into default class? I tried hasProperty({prop1}) and it returned true. However, property({prop1}) resulted prop1 as write-only exception.
If you use a method property(String) in task exampleTask{} block, it is the method of Task#property(String). The method Task#property(String) tries to find property from task object, and it’s not property given by command line(-Pprop1=xxx).
If you use a method property(String) outside of task exampleTask{} block, it is the method of Project#property(String). It will return property given by command line(-Pprop1=xxxx).
The detail information is available at Gradle’s dsl document.
Because you didn’t write your script, class definition and stacktraces, I guessed. And I guessed you might have created class as follows…
public class ExampleClass extend DefaultTask {
private String prop1;
@TaskAction public void doWork() {
System.out.println ("prop1 -> [" + prop1 + "]");
}
// setter/getter
}
And I guess you might have created script as follows…
task exampleTask(type: ExampleTask) {
def existsProp = hasProperty('prop1') // -> Task#hasProperty and it will return true because class ExampleTask has field prop1
prop1 = property('prop1') // -> this will set null to ExampleTask#prop1, because this property method is Task#property method and returns null because ExampleTask#prop1 has no default value.
}
In the class and scripts above, while you run Gradle with a parameter -Pprop1=xxxx, the task cannot retrieve the parameter value.
In my understanding, you want to give a parameter to task from command, don’t you?