4

Is it possible to declare or change Java variables accessible via code with gradle?

I found Is it possible to declare a variable in Gradle usable in Java? and it tells me how to declare variables accessible via Java code for Android projects.

Is it possible to do the same with "normal" Java projects? I want to set a variable depending on which task is executed.

Thanks for your help!

3
  • 1
    A common solution is to generate/detokenize a resource file (e.g. properties file) and read that from the Java code. Commented Sep 1, 2014 at 21:27
  • @PeterNiederwieser I already thought about that but I don't find a solution for this :( Do you have a reference to a code snippet or a snippet itself? Thanks a lot anyway! Commented Sep 1, 2014 at 21:34
  • 1
    chimera.labs.oreilly.com/books/1234000001741/… Instead of declaring a new Copy task, you'd configure the Java plugin's processResources task. Commented Sep 1, 2014 at 21:41

1 Answer 1

5

Thanks to @PeterNiederwieser I solved my problem:

In my gradle.build I use:

task usernameMaxio(type: Copy) {
  from 'src/main/resources/properties'
  into 'build/resources/main/properties'
  expand([
    username: 'Maxio'
  ])
}

and I access it via:

Properties properties = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream("properties/app.properties");
try {
    properties.load(stream);
} catch (IOException | NullPointerException e) {
    WebOptionPane.showMessageDialog(null, "Couldn't read app.properties", "Fehler",
                                    WebOptionPane.ERROR_MESSAGE);
    e.printStackTrace();
    return;
}
name = properties.getProperty("username");

And in my app.properties:

username=${username}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.