5

Hi Maybe this is a foolish question but i am not much familiar with groovy and gradle and can't get the exact answer.

  public class Config{
   public static final String APPLICATION_ID="com.app.dracula";
   public static final int VERSION_CODE=1;
    public static final String VERSION_NAME="1.0.0";
}

I have class like above . Can i use this class in build.gradle to assign the all fields(Watch out the fields names).

I know i can create BuildConfigField from a properties file which i am doing right now . But out of curiosity is there a way to use a .java class or interface in build.gradle? Can i achieve something like .

 defaultConfig {
    applicationId Config.APPLICATION_ID
    minSdkVersion 16
    targetSdkVersion 26
    versionCode Config.VERSION_CODE
    versionName Config.VERSION_NAME
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true
}

Don't Confused by above code this is just an metaphor of what i want to achieve .

ADM
  • 20,406
  • 11
  • 52
  • 83
  • 2
    The way you are trying is not possible as JAVA classes are yet not compiled and hence you can not use java class variables or objects. You should initiate a class within Gradle file. For eg:- https://stackoverflow.com/a/26314875/3594268 Then maybe you can use its variables. NOTE:-Not tested. – Abhinav Aggarwal Jun 15 '18 at 11:11
  • Thats seems a fair reason for why i can't do that . Thx . – ADM Jun 15 '18 at 11:17
  • 1
    Take a look at https://docs.gradle.org/current/userguide/custom_tasks.html – E.Abdel Jun 15 '18 at 11:17
  • I'd argue doing it the opposite way around would make more sense. See: https://stackoverflow.com/questions/17197636/is-it-possible-to-declare-a-variable-in-gradle-usable-in-java – Michael Dodd Jun 15 '18 at 11:19
  • Thx Michael I am the same method right now . Are you satisfied with @ Abhinav Aggarwal's Comment ? – ADM Jun 15 '18 at 11:20
  • 1
    if you just want to access those variable as constants then there is no need for creating a class, just store them in gradle.properties and and configure them in build.gradle like this `buildConfigField("String", "APP_ID","\"${APP_ID}\"")` – Ashish Sharma Jun 15 '18 at 11:23
  • @AshishSharma Yeah thats what i am doing right now . But requirement is kind of having a single file which have only the configurations and nothing else . So i dropped `gradle.properties` and i created my own properties file . And its working fine. But i was just curious about using a `.java` class or interface. – ADM Jun 15 '18 at 11:35
  • 1
    ok, yeah creating your own .properties file is a good choice. Never thought about using .java, i'll dig into it, if I find something useful i'll let you know. – Ashish Sharma Jun 15 '18 at 13:04

0 Answers0