gradle基于副本创建新的java类

时间:2015-08-18 14:18:27

标签: java regex replace gradle rename

我在专用包中有一个旧bean对象的结构

我想将它们复制到测试文件夹中,所以当我更新它们时,我可以确保新版本与新版本兼容

为避免任何命名问题,旧bean将在复制期间重命名 这使得副本但是类无法编译,因为className!= filename

task saveOldBean(type: Copy) {
  from('src/main/java/project/bean/') {
      include '**/*Bean.java'
  }
  into 'src/test/java/project/bean/'
  rename '(.*).java', '$1Old.java'
}

所以我尝试使用相同类型的功能(即regexp)替换文件中的ClassName

task saveOldBean(type: Copy) {
   from('src/main/java/project/bean/') {
     include '**/(.*Bean).java'
     filter(ReplaceTokens, tokens: [$1: $1Old])
   }
   into 'src/test/java/project/bean/'
  rename '(.*).java', '$1Old.java'
}

这失败了,所以如果你有任何建议要做这个"重命名"工作,欢迎你

1 个答案:

答案 0 :(得分:0)

经过一些尝试后,这是一个实现

task backupBean(type: Copy) {
  def TAG_PREVIOUS="Backup";
  def newEnd = "${TAG_PREVIOUS}.java";

  from('src/main/java') {
    include '**/*Bean.java'
  }
  into 'src/test/java'
  rename { String fileName -> 
    fileName.replace('.java', newEnd)
  }

  eachFile {  FileCopyDetails fileInfo ->
    def fileName = fileInfo.name;
    def oldClassName =  fileName.replace(newEnd, "");
    def newClassName = fileName.substring(0, fileName.indexOf(".java"));

    filter{ it.replaceAll("$oldClassName","${newClassName}")}
    filter{ it.replaceAll("public final class","/*${version}*/\npublic final class")}

    println "save [$oldClassName] to [$newClassName]"
  }
}