How to programmatically rename a method using JDT

你。 提交于 2019-11-30 20:37:52

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

  1. Download the release you want, with source code. In particular, you want the source for the JDT plugins, which is included in the 'classic' release. All of the following is based on 4.2.1.
  2. Boot up in to an empty workspace.
  3. File->Import: Plug-ins and Fragments
  4. Import from "The active target platform", "Select from all...", "Projects with source folders"
  5. Select 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. That's for the overall rename refactoring though, it can rename anything from methods to files. More relevant for you is RenameSupport.create(IMethod, String, int).

You can see there that a RenameRefactoring class is created around either a processor, either a RenameVirtualMethodProcessor or a RenameNonVirtualMethodProcessor, and then sent to a new instance of RenameSupport. RenameSupport handles all the UI to configure your refactoring, but since you're doing it programatically you just need the RenameRefactoring and the processor, configured using the various processor.set*() methods.

Now you have a configured instance of RenameRefactoring. Now what? The actual operation in Eclipse is executed across two Job implementations. Take a look at RefactoringExecutionHelper.Operation and PerformChangeOperation for the details.

What does this all boil down to? Leaving aside all the fine details of exception handling, having an undo stack, and workspace checkpoints, you could rename a 'virtual' method using these 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's a lot of support code in there for undo, progress bars, async execution, workspace checkpoints etc, which you may or may need depending on how you want to run this. But that's the guts of how to run the refactoring.

i think this will help you if that what you are looking for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!