Search code examples
refactoringeclipse-jdtabstract-syntax-treeeclipse-plugin

eclipse: change the package of a class via ast


How can I programmatically change the package of a class in Eclipse. In a way to have the same result as when drag-dropping the class into another package. I assume it must be done using AST, but can't find a proper tutorial describing it.


Solution

  • Ok, I will answer to my own question (like a Sir:)). I had to debug into Eclipse and here is how it works:

    CompositeChange composite = new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move);
    MoveCuUpdateCreator creator = new MoveCuUpdateCreator(new ICompilationUnit[] {compUnit}, (IPackageFragment) newContainer);
    TextChangeManager fChangeManager = creator.createChangeManager(new SubProgressMonitor(pm, 1), new RefactoringStatus());
    composite.merge(new CompositeChange(RefactoringCoreMessages.MoveRefactoring_reorganize_elements, fChangeManager.getAllChanges()));
    Change change = new MoveCompilationUnitChange(compUnit, (IPackageFragment) newContainer);
    if (change instanceof CompositeChange) {
        composite.merge(((CompositeChange) change));
    } else {
        composite.add(change);
    }
    composite.perform(pm);