Is it possible to declare a variable in Gradle usable in Java?

后端 未结 9 1387
春和景丽
春和景丽 2020-11-22 09:11

Is it possible to declare a variable in Gradle usable in Java ? Basically I would like to declare some vars in the build.gradle and then getting it (obviously) at build time

9条回答
  •  一个人的身影
    2020-11-22 09:40

    None of the above answers gave me any guidelines so I had to spend two hours learning about Groovy Methods.

    I wanted be able to go against a production, sandbox and local environment. Because I'm lazy, I only wanted to change the URL at one place. Here is what I came up with:

     flavorDimensions 'environment'
        productFlavors {
            production {
                def SERVER_HOST = "evil-company.com"
                buildConfigField 'String', 'API_HOST', "\"${SERVER_HOST}\""
                buildConfigField 'String', 'API_URL', "\"https://${SERVER_HOST}/api/v1/\""
                buildConfigField 'String', 'WEB_URL', "\"https://${SERVER_HOST}/\""
                dimension 'environment'
            }
            rickard {
                def LOCAL_HOST = "192.168.1.107"
                buildConfigField 'String', 'API_HOST', "\"${LOCAL_HOST}\""
                buildConfigField 'String', 'API_URL', "\"https://${LOCAL_HOST}/api/v1/\""
                buildConfigField 'String', 'WEB_URL', "\"https://${LOCAL_HOST}/\""
                applicationIdSuffix ".dev"
            }
        }
    

    Alternative syntax, because you can only use ${variable} with double quotes in Groovy Methods.

        rickard {
            def LOCAL_HOST = "192.168.1.107"
            buildConfigField 'String', 'API_HOST', '"' + LOCAL_HOST + '"'
            buildConfigField 'String', 'API_URL', '"https://' + LOCAL_HOST + '/api/v1/"'
            buildConfigField 'String', 'WEB_URL', '"https://' + LOCAL_HOST + '"'
            applicationIdSuffix ".dev"
        }
    

    What was hard for me to grasp was that strings needs to be declared as strings surrounded by quotes. Because of that restriction, I couldn't use reference API_HOST directly, which was what I wanted to do in the first place.

提交回复
热议问题