Alex Rivera | Logout

Automatically remove explicit package declarations with import statements in Java

Asked 2010-01-26T20:50:50.347
19

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 looks like the code was reverse engineered. Is there a good tool for Java that refactors the code so that the explicitly typed package prefixes are removed from class references and moved into import statements.

Thank you in advance.

EDIT:

I think an example will help. I want to have the imports at the top, and I don't care how many imports there are.

javax.swing.JButton button1 = new javax.swing.JButton();

Imagine the code above but absolutely everywhere in thousands upon thousands of lines of code amongst thousands of class files. I would like to be able to remove all of the prefixes and just have a nice import javax.swing.JButton; at the top of each class file.

Edit
Report

1 Answer

1

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)
  }
 }
}
answered 2010-12-02T16:12:12.583

Your Answer