Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 535
Fahim Avatar asked May 30 '26 21:05

Fahim


1 Answers

I'm unclear as whether you wish to perform this renaming across the board (i.e. all methods in all classes) or just to specific classes which you would identify manually. Assuming the latter, I would recommend that you:

  1. Use the Java reflection API java.lang.reflect to identify all methods defined within the particular class that requires local variable renaming.
  2. Iterate across all methods. For each method, use the org.eclipse.jdt.core API to descend through the hierarchy of compilation elements, selecting locally scoped variable definitions. Get the name of the variable for the compilation unit.
  3. Generate your new variable name. Something like: Old ==> OldRenamed. Apply whatever renaming heuristic you wish at this point.
  4. Invoke the Eclipse development kit org.eclipse.jdt.ui.refactoring API methods to do the variable renaming within the method. Effectively you would be invoking the Eclipse Rename Variable functionality headlessly by using this API.

That should do the trick.

like image 72
Jeff Knaus Avatar answered Jun 01 '26 10:06

Jeff Knaus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!