Eclipse - How to "Change package declaration to ...." across an entire project

I just had the same problem so I wrote a bash script to do it.

function java-package-update { 
  for path in $(find $1 -type f -name "*.java"); do 
    D=$(dirname $path); 
    F=$(basename $path); 
    P=$(echo $D|tr '/' '.'); 
    if egrep -q '^\s*package\s*' $path; then 
      sed -i '' '/^\s*package\s*/s/^\(\s*package\s*\)[^;]*\(;.*\)/\1 '$P'\2/' $path; 
    else 
      echo >&2 "no package in $path";
    fi; 
  done; 
}

The sed command used is the one on OSX. If you're using gnu sed, then you don't need the '' paramater after the -i.

Just paste it in and run it on the directory containing your source. Backup your source first unless you're very brave.

Example:

$ cd /home/me/proj/fred/src
$ ls
com
$ cp -a com com.backup
$ java-package-update com
$ # fingers crossed
$ diff -ru com.backup com

I really should start doing this stuff in a more modern language like perl :)


Right click on the package, select Refactor > Rename. This will update all source files with the new package name.


For this particular problem (which usually comes with auto generated artifact files), I found a neat solution.

So if the issue is that your package declarations is "package abc;" in 200 files, and you want it to be "package com.aa.bb.cc.abc;"

Then in eclipse, Search->File for "package abc;" in required folder or pkg or whole workspace. Don't select Search option but select "Replace" and then put "package com.aa.bb.cc.abc;" when it asks for the replacement after search. Should do the trick.


If the package declarations are no longer valid, then all such invalid declarations would appear in the Problems view in Eclipse. If you do not see this view, you can open it from Window-> Show View -> Other... -> Problems (under the General tab).

You can filter on problems in the Problems view and correct easily correctable ones, by choosing the Quick fix option in the context menu (available on a right-click). In your case you should see something similar to the screenshot posted below:

Quick fix for incorrect packages

Applying the quick fix options is trivial, as long as you know which one is correct - you would either have to change the package declaration in the class, or the location of the class itself. Unfortunately there is no option to fix the issue across multiple units at one go; you will have to apply the quick fix for every problem.

If you want to filter on problems of only this variety, consider configuring the Problems view to show all errors that have the text content "does not match the expected package" in the error text, as demonstrated in the following screenshots:

Configure Problem Contents

Eclipse Configure Package Problems