我目前正在开发一个 Eclipse 插件,它可以让我使用手势触发重构。我一直在尝试在 Eclipse 中以编程方式触发“提取方法”一段时间,但我经常遇到问题。我在寻找解决方案时发现的大多数建议都需要使用内部类。
我现在被困在这个代码模板上。问题是我找不到可以将要提取的代码作为 ISelection 或类似内容的地方。
RefactoringContribution rc = RefactoringCore.getRefactoringContribution(IJavaRefactorings.EXTRACT_METHOD);
ExtractMethodDescriptor rd = (ExtractMethodDescriptor) rc.createDescriptor();
rd.setProject(staticHelper.getIProject().getName());
//There should be some more rd.setXXXXX() here.
RefactoringStatus rs = new RefactoringStatus();
try {
Refactoring r = rd.createRefactoring(rs);
IProgressMonitor pm = new NullProgressMonitor();
r.checkInitialConditions(pm);
r.checkFinalConditions(pm);
Change change = r.createChange(pm);
change.perform(pm);
}
catch(Exception e) {e.printStackTrace();}
}
以下方法有效,但它使用内部 API:
@SuppressWarnings("restriction") //Works but is INTERNAL USE ONLY
public static void extractMethodRefactoring() {
ITextSelection selection = staticHelper.getITextSelection();
int start = selection.getOffset();
int length = selection.getLength();
//The following line is part of the internal API
ExtractMethodRefactoring tempR = new ExtractMethodRefactoring(staticHelper.getICompilationUnit(), start, length);
try {
NullProgressMonitor pm = new NullProgressMonitor();
tempR.checkAllConditions(pm);
Change change = tempR.createChange(pm);
change.perform(pm);
} catch (Exception e) {e.printStackTrace();}
}
这同样需要内部类 ExtractMethodRefactoring,但不应使用该类。