How can I have separate debug and release versions of gradle project that pull in different versions of the same class?

Viewed 370

I have two versions of the same Java class (same name / methods). Since it's Java, both .java files have the same name. I want to configure gradle in such a way that I can build a "debug" version of my application that pulls in one of these files, and a "production" version of my application that pulls in the other one. How would I go about doing this?

This class has only static methods. I don't ever want to make an instance of this class. I additionally don't want to add the overhead of an if statement in each of the methods on this class to check which version I'm in.

4 Answers

Following @JFabianMeier's answer you could use 4 projects:

  1. with the production version class
  2. with the debug version class
  3. with code that uses either of the two, parameterized according to Migrating Maven profiles ... → Example 6. Mimicking the behavior of Maven profiles in Gradle. (I'm also a Maven guy and therefore can't tell you exactly how to do it in Gradle.)
  4. a multi-project with 1./2./3. as sub[-]projects for building all of them in one go, maybe parameterized to build just 1.+ 3. or 2.+ 3.

Have you tried creating production and debug source directories/sets? According to the docs you can use multiple directories when specifying source directories in your source set. Try dropping the different versions of your class in their respective production/debug source directories.

I haven't tested myself (not sure about the syntax), but this is based on the Gradle's Java compilation documentation.

sourceSets {
    // Could also name this production
    main {
        java {
            srcDirs ['src/main/java', 'src/prod/java']
        }
    }
    debug {
        java {
            srcDirs ['src/main/java', 'src/debug/java']
        }
    }
}

You could do the following:

  • Put the class into a separate project (so generate a separate jar from it)
  • Then you can have two different jars, for production and debugging
  • Then you can pull either one or the other jar in gradle depending on a parameter.

Alternatively, you could look into template engines like Velocity which allow you to generate source code during the build depending on variables and then compile it.

Related