我目前正在开发一个Eclipse Plug-In,它可以让我使用手势触发重构。 我一直试图在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,不应该使用它。