Organise Imports Eclipse Method

断了今生、忘了曾经 提交于 2019-12-10 21:08:44

问题


I need to know which method is called inside eclipse when I press "CTRL+ SHIFT + O" (Organise Imports), in order to invoke it after a code generation. What the name of this method and where can I find it (Package.Interface)

Thanks


回答1:


"Organize Imports" action is contributed by org.eclipse.jdt.ui.actions.OrganizeImportsAction, which, in turn, calls org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.




回答2:


Finaly Managed to do it with this code (targetSite is a IWorkbench site initialized at the ame time as shell):

@Override
public void postLaunchAction(final IProject project, final IProgressMonitor monitor) throws CoreException {

    super.postLaunchAction(project, monitor);

    Runnable job = new Runnable() {

        @Override
        public void run() {
            OrganizeImportsAction org = new OrganizeImportsAction(SpringServicesAction.this.targetSite);
            try {
                IJavaProject prj = null;
                if (project.hasNature("org.eclipse.jdt.core.javanature")) {
                    prj = JavaCore.create(project);
                }

                IStructuredSelection selection = new StructuredSelection(prj);
                org.run(selection);
            } catch (CoreException ce) {
                ce.printStackTrace();
            }
        }

    };

    this.shell.getDisplay().syncExec(job);
}



回答3:


For reference, this is how I did it:

I made a large automated refactor in the codebase in our project. Due to a (i think so) bug in eclipse with refactoring static methods which are staticly imported in another file, i had to call organize imports after each refactor (also because I commit every move to git automaticly):

private void organizeImports(ICompilationUnit cu)
        throws OperationCanceledException, CoreException {

    cu.becomeWorkingCopy(null);
    CompilationUnit unit = cu.reconcile(AST.JLS4, false, null, pm);
    NullProgressMonitor pm = new NullProgressMonitor();

    OrganizeImportsOperation op = new OrganizeImportsOperation(cu, unit,
            true, true, true, null);

    TextEdit edit = op.createTextEdit(pm);
    if (edit == null) {
        return;
    }

    JavaModelUtil.applyEdit(cu, edit, true, pm);
    cu.commitWorkingCopy(true, pm);
    cu.save(pm, true);
}

Disadvantagde: Discouraged access. If somebody has an idea to call this action properly without creating a new runnable and without using a shell etc., please comment.



来源:https://stackoverflow.com/questions/10008492/organise-imports-eclipse-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!