Filtering a Java Class Using Gradle

I have the following class in src / main / java / com / company / project / Config.java:

public class Config {

  public static final boolean DEBUG = true;

  ...
}

so in some other class I can do the following, knowing that the java compiler will split the if () statement if it evaluates to false:

import static com.company.project.Config.DEBUG

if (DEBUG) {
  client.sendMessage("something");

  log.debug("something");
}

In Gradle, what is the best way to filter and change the DEBUG value in Config.java at compile time without changing the source file?

So far I am thinking:

  • Create an updateDebug task (type: Copy) that filters DEBUG and copies Config.java to a temporary location
  • Exclude source file Config.java from sourceSets and enable temporary
  • Make compileJava.dependsOn updateDebug

Is it possible? Is there a better way?

+4
1

, src/main/java/com/company/project/Config.java:

public class Config {

  public static final boolean DEBUG = true;

  ...
}

Gradle, :

//
// Command line: gradle war -Production
//
boolean production = hasProperty("roduction");

//
// Import java regex
//
import java.util.regex.*

//
// Change Config.java DEBUG value based on the build type
//
String filterDebugHelper(String line) {
  Pattern pattern = Pattern.compile("(boolean\\s+DEBUG\\s*=\\s*)(true|false)(\\s*;)");
  Matcher matcher = pattern.matcher(line);
  if (matcher.find()) {
    line = matcher.replaceFirst("\$1"+(production? "false": "true")+"\$3");
  }

  return (line);
}

//
// Filter Config.java and inizialize 'DEBUG' according to the current build type
//
task filterDebug(type: Copy) {
  from ("${projectDir}/src/main/java/com/company/project") {
    include "Config.java"

    filter { String line -> filterDebugHelper(line) }
  }
  into "${buildDir}/tmp/filterJava"
}

//
// Remove from compilation the original Config.java and add the filtered one
//
sourceSets {
  main {
    java {
      srcDirs ("${projectDir}/src/main/java", "${buildDir}/tmp/filterJava")
      exclude ("com/company/project/Config.java")
    }

    resources {
    }
  }
}

//
// Execute 'filterDebug' task before compiling 
//
compileJava {
  dependsOn filterDebug
}

, , , , , / (build.gradle).

+1

All Articles