How to programmatically rename a method using JDT

My goal is to programmatically call the Refactor >> Rename Eclipse command for the method inside the Java source file. Renaming a method as such should also apply the change to all instances in which this method is / is used.

I believe that JDT has a Refactoring API, but cannot find any documents or tutorials for the same.

Can someone point me in the right direction.

Edit: No change is required at run time.

+7
source share
2 answers

I think your most promising approach is to switch to the eclipse source code.

  • Download the source release you need. In particular, you need a source for JDT plugins, which is included in the "classic" version. All of the following is 4.2.1 .
  • Boot into an empty workspace.
  • File-> Import: plugins and snippets
  • Import from Active Target Platform, Select from All ..., Projects with Source Folders
  • Choose at least org.eclipse.jdt.ui and org.eclipse.ltk.core.refactoring.

The starting point corresponding to Refactor >> Rename is org.eclipse.jdt.ui.actions.RenameAction . However, for general renaming refactoring, you can rename any of the methods to files. More relevant to you is RenameSupport.create(IMethod, String, int) .

You can see that the RenameRefactoring class is created around any processor, either RenameVirtualMethodProcessor , or RenameNonVirtualMethodProcessor , and then sent to a new instance of RenameSupport . RenameSupport handles the entire user interface to set up refactoring, but since you do it programmatically, you just need RenameRefactoring and a processor configured using various processor.set*() methods.

You now have a customized instance of RenameRefactoring . Now what? The actual operation in Eclipse is performed in two implementations of Job. Take a look at RefactoringExecutionHelper.Operation and PerformChangeOperation for details.

What does it all come down to? Leaving aside all the minor details of exception handling, having a cancellation stack and breakpoints in the workspace, you can rename the "virtual" method using the following steps:

 IMethod methodToRename = <....> RenameMethodProcessor processor = new RenameVirtualMethodProcessor(methodToRename) processor.setUpdateReferences(true); processor.setNewElementName("newMethodName"); RenameRefactoring fRefactoring = new RenameRefactoring(processor); fChange= fRefactoring.createChange(new NullProgressMonitor()); fChange.initializeValidationData(new NullProgressMonitor()); fChange.perform(new NullProgressMonitor()) 

There is a lot of support code for cancellation, progress indicators, asynchronous operations, workspace breakpoints, etc. that you may need or may need, depending on how you want to run them. But it’s the courage to start refactoring.

+4
source

I think this will help you if you are looking for it.

0
source

All Articles