用 Gradle 过滤 Java class

Filtering a Java class with Gradle

我在 src/main/java/com/company/project/Config 中有以下 class。java:

public class Config {

  public static final boolean DEBUG = true;

  ...
}

以便在其他一些 class 中我可以执行以下操作,知道 java 编译器将在计算结果为 false 时删除 if() 语句:

import static com.company.project.Config.DEBUG

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

  log.debug("something");
}

在Gradle中,在不修改原始文件的情况下,在编译时过滤和更改Config.java中的DEBUG值的最佳方法是什么?

到目前为止我在想:

  1. 创建一个过滤 DEBUG 的任务 updateDebug(type:Copy) 并将 Config.java 复制到一个临时位置
  2. 从 sourceSets 中排除原始 Config.java 文件并包含临时文件
  3. 制作compileJava.dependsOn更新调试

以上可能吗? 有没有更好的方法?

回答我自己的问题,给定 class 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) 控制 development/production 构建。