Rizz
Rizz

Reputation: 56

Triggering 'extract method' in Eclipse Refactoring/LTK API

I am currently developing an Eclipse Plug-In that will let me trigger refactorings, using gestures. I've been trying to trigger 'extract method' programmatically in Eclipse for a while now but I am constantly running into issues. Most suggestions I have found while searching for a solution require the use of internal classes.

I am now stuck at this code template. The issue is that I find no place where I could give the code I want to extract as ISelection or something similar.

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();}
}

The following method works, but it uses the internal 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();}

}

Again this requires the internal class ExtractMethodRefactoring, which should not be used.

Upvotes: 0

Views: 382

Answers (0)

Related Questions