Search code examples
javaeclipse-pluginidentifierrenaming

identifier rename in java program


I need to programmatically rename identifiers within a given scope, for example, a method in java program. For example, given the following java function:

public void doSomething(){
   int x = 10;
   int y = x * 2;
   int z = x + y;
}

after renaming the variables (x to a, y to b, and z to c) I should obtain the following function:

public void doSomething(){
   int a = 10;
   int b = a * 2;
   int c = a + b;
}

How can I programmatically implement such renaming of identifiers and their references?

I have been looking into Eclipse AST and Java Model. In either case I have to implement search for all occurrences of any given identifier, and then replace them. I am wondering if there is a better way to do this (how the Eclipse Refactoring UI supports such variable renaming)? Or, should I look into the Language Toolkit (org.eclipse.ltk.core.refactoring)? Any tutorial, sample code, or suggestion?

Please help.


Solution

  • I am able to rename using the following code.

    RenameSupport renameSupport = RenameSupport.create(field, newName, RenameSupport.UPDATE_REFERENCES);
    renameSupport.perform(workbench.getShell(), workbench);
    

    But it applies the changes to the actual source files. Is there Anyway that can be prevented? I just need the renamed code internally, must not change the actual source.