Andy Thomas
Andy Thomas

Reputation: 86449

How to globally replace one annotation type with another?

I would like to replace one annotation type with another, throughout a large codebase.

This requires updating import statements and the annotations themselves.

Is there a mechanism to do this in the Eclipse IDE other than possibly naive textual search/replace?

For example:

import edu.umd.cs.findbugs.annotations.NonNull;
...
    public @NonNull Integer
    foo( @NonNull Integer arg0 ) { ... }

Needs to be updated to:

import javax.annotation.Nonnull;
...
    public @Nonnull Integer
    foo( @Nonnull Integer arg0 ) { ... }

Upvotes: 4

Views: 252

Answers (1)

gknicker
gknicker

Reputation: 5569

It's easy in Eclipse.

  1. From the Search menu choose File...
  2. Set Containing text: to, for example, edu.umd.cs.findbugs.annotations.NonNull and click the Search button.
  3. In the Search results view, use the context menu Remove Selected Matches as necessary to remove matches that shouldn't be replaced
  4. Right-click one of the results (context menu) and choose Replace all...
  5. In the Replace Text Matches dialog, enter the replacement phrase javax.annotation.Nonnull in the With: box and click OK

The above would replace the imports, then you'd go through these steps again to replace the @NotNull uses.

If you prefer to use the refactoring tool, there is a way to go about this. But it's pretty involved, especially if you don't have access to the source code of the identifier you wish to move away from.

  1. If the identifier being referenced is not under your control, then put it under your control through whatever manipulation necessary. For example, let's say you're using a third-party annotation edu.umd.cs.findbugs.annotations.NonNull from a jar file. Ideally you'd have access to the source code, but you could also stub out the annotation. In any case, you'd remove the third-party jar file from your project and replace it with source code in your project, then get a clean build.
  2. With the source in question now under your control, Refactor->Rename... it to the target name then Refactor->Move... it to the target package. You might have to create the package in your project first.
  3. Finally, if applicable, delete the imposter you've just created, so that the real one can take its rightful place.
  4. Any other temporary package cleanup as necessary.

Upvotes: 2

Related Questions