0

ALL,

Lets say I have a JAVA project with the gradle. In the buidl.gradle file I have a property defined like this:

packageName = "svc.pvtbroker" //name of the package

Is there a simple way I can use this "packageName" inside the Java source code?

TIA!!

Igor
  • 5,620
  • 11
  • 51
  • 103
  • you can do something like this i guess https://stackoverflow.com/questions/17197636/is-it-possible-to-declare-a-variable-in-gradle-usable-in-java – Arun Prasat Jun 28 '19 at 18:35

2 Answers2

1

You can generate either a java file or a resource and add the generated folder to either the resources or compiled sources.

Eg: let's say we wanted the packageName available via a static method at runtime

task generateJava {
   // set inputs/outputs for up to date checks 
   inputs.property('packageName', project.property('packageName')) 
   outputs.dir "$buildDir/generated/java" 
   doLast {
      File f = file("$buildDir/generated/java/GradleProperties.java"
      f.parentFile.mkdirs()
      f.text = 
"""
public class GradleProperties {
   public static String getPackageName() {
      return \"${packageName}\";
   } 
}
"""
   } 
} 
// add the dir to the java sources 
sourceSets.main.java.srcDir "$buildDir/generated/java" 
// wire the task into the DAG
compileJava.dependsOn generateJava
lance-java
  • 25,497
  • 4
  • 59
  • 101
0

Inside .app gradle declare your property like this:

    defaultConfig {
        ...
        buildConfigField("String", "API_KEY", "123456789")
    }

then import your property in your java source code in this way:

import static yourpackage.BuildConfig.API_KEY;

SUGGEST I also declare my keys inside gradle.properties

API_KEY_INSIDE_GRADLE_PROPERTIES="123456789"

in this way you can use BuildConfigField like this:

    defaultConfig {
        ...
        buildConfigField("String", "API_KEY", API_KEY_INSIDE_GRADLE_PROPERTIES)
    }

Hope it helps.

Andrea Ebano
  • 563
  • 1
  • 4
  • 16
  • @AnfreaEbano, what is the purpose of declaring it twice? I want to avoid it and have it only in one place... – Igor Jun 28 '19 at 19:48
  • If you want all properties in one place i think gradle.properties is the right piace. https://medium.com/@rafamatias/gradle-android-build-variables-done-right-d0c0e296ee93 – Andrea Ebano Jun 28 '19 at 20:03