How to edit write-only property as readable and writable

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

task(type: org.ttg.examleClass){
//some actionns

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.

I will appreciate any kind of help.

Where do you use a method property(String)?

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.

Thanks for your response @Shinya_Mochida. I use it inside of exampleTask class.

Could you please expand what you mean by properly given? I use -P{property1}={property1Val}

hasProperty({property1}) returned true. What triggers to make it as write only property for task class?

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?

If so, you have to change script as follows.

task exampleTask(type: ExampleTask) {
    prop1 = project.hasProperty('prop1') ?'prop1') : 'default value'

If I have mistaken your question and your intent, please let me know, and show me your class definition and build script.

Thanks again @Shinya_Mochida. It worked! I didn’t originally define task in a way you suggested.