Automatically remove explicit package declarations with import statements in Java

前端 未结 8 1136
不思量自难忘°
不思量自难忘° 2021-01-07 19:46

I have a project created by others that includes thousands of class files and has the package names explicitly typed out for every reference to any of their classes. It look

8条回答
  •  醉酒成梦
    2021-01-07 19:51

    I had the same problem with axis generated files, and I wrote a small groovy script to do this. I doesn't do everything (you have to use organize imports in eclipse after you run it), and I haven't tested it very well, so use it carefully. It's also limited to lowercase package names and camel-cased class names, but it may be a good starting point

    def replaceExplicitPackageNamesInFile(File javaFile){
     eol = org.codehaus.groovy.tools.Utilities.eol()
    
     newFile = ""
     explicitImportExpr = /([^\w])(([a-z0-9]+\.)+)([A-Z][a-zA-Z0-9]+)/
     imports = ""
     javaFile.eachLine { 
      line = it.replaceAll(explicitImportExpr, {
       Object [] match ->
       imports += "import ${match[2]+match[-1]};${eol}"
       match[1]+match[-1]
      })
      newFile += line+"${eol}" 
     }
     newFile2 = ""
     newFile.eachLine { line ->
      newFile2 +=
       line.replaceAll(/(^\s*package.*$)/, {
        Object [] match ->
        match[0] + eol + imports
       } ) + eol
     }
     javaFile.setText(newFile2)
    }
    
    def replaceExplicitPackageNamesInDir(File dir){
     dir.eachFileRecurse {
      if (it.isFile() && it.name ==~ /.*\.java\z/){
       println "Processing ${it.absolutePath - dir.absolutePath}"
       replaceExplicitPackageNamesInFile(it)
      }
     }
    }
    

提交回复
热议问题