Is there any Eclipse refactoring API that I can call programmatically?

后端 未结 2 1563
忘掉有多难
忘掉有多难 2020-11-29 04:28

I need to refactor code in a wide term. I know that from inside the Eclipse IDE I can refactor my classes. But is there any API that I can use in a java project so that I ca

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 04:42

    The answer below is great, but I answered with a wider perspective for the people who need a more bulky and tasty crunch of this wonderful cake:

        RefactoringStatus status = new RefactoringStatus();
        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IWorkspaceRoot root = workspace.getRoot();
        IProject[] projects = root.getProjects();
    

    then:

    for (ICompilationUnit unit : mypackage.getCompilationUnits()) {
        IType primary = unit.findPrimaryType();
        IMethod[] methods = primary.getMethods();
        int i = 1;
        for (IMethod method : methods) {
            if (method.isConstructor()) {
                continue;
            }
        makeChangetoMethods(status, method,"changedMethodVersion_" + i);
        ++i;
        }
    }
    

    After that:

    IProgressMonitor monitor = new NullProgressMonitor();
    status = new RefactoringStatus();
    Refactoring refactoring = performMethodsRefactoring(status, methodToRename, newName);
    

    then:

    Change change = refactoring.createChange(monitor);
    change.perform(monitor);
    

    find below the code for setting the descriptor:

    String id = IJavaRefactorings.RENAME_METHOD;
    RefactoringContribution contrib = RefactoringCore.getRefactoringContribution(id);
    RenameJavaElementDescriptor desc = contrib.createDescriptor();
    desc.setUpdateReferences(true);
    desc.setJavaElement(methodToRename);
    desc.setNewName(newName);
    desc.createRefactoring(status);
    

提交回复
热议问题