简体   繁体   English

Java以编程方式导入

[英]Java Imports Programmatically

I have built an eclipse plugin, which would generate a new Java project with new classes. 我已经构建了一个eclipse插件,它将生成一个带有新类的新Java项目。

Once the classes are generated, the plugin must traverse through each class and do an automatic "organize imports" action (It must be done programmatically - not by Eclipse SaveAction option). 生成类后,插件必须遍历每个类并执行自动“组织导入”操作(必须以编程方式完成 - 而不是通过Eclipse SaveAction选项)。

I have tried a code segment for doing the same. 我尝试过代码段来做同样的事情。

public void organizeImports(IProject iProj) {

    try {

        IPackageFragment[] packages = JavaCore.create(iProj)
                .getPackageFragments();
        for (IPackageFragment mypackage : packages) {
            if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) {

                for (ICompilationUnit currentCompilationUnit : mypackage
                        .getCompilationUnits()) {


                    try {
                        System.out.println("CompilationUnit: " + currentCompilationUnit);
                          IEditorPart editorPart = PlatformUI.getWorkbench()
                                .getActiveWorkbenchWindow().getActivePage()
                                .getActiveEditor();
                        PlatformUI.getWorkbench().getActiveWorkbenchWindow()
                                .getActivePage().activate(editorPart);


                        final IHandlerService handlerService = (IHandlerService) PlatformUI
                                .getWorkbench().getService(
                                        IHandlerService.class);

                        IHandler handler = new AbstractHandler() {
                            public Object execute(ExecutionEvent event)
                                    throws ExecutionException {
                                System.out.println("Inside execute");
                                return null;
                            }
                        };
                        handlerService
                                .activateHandler(
                                        "org.eclipse.jdt.ui.edit.text.java.organize.imports",
                                        handler);

                        handlerService
                                .executeCommand(
                                        "org.eclipse.jdt.ui.edit.text.java.organize.imports",
                                        null);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

            }

        }

    } catch (Exception e1) {
        e1.printStackTrace();
    }

} 

Now it makes imports successfully for few classes, while for others it throws something like this 现在它为几个类成功导入,而对于其他类,它会抛出类似的东西

MESSAGE A handler conflict occurred.  
This may disable some commands.!MESSAGE Conflict for 'org.eclipse.jdt.ui.edit.text.java.organize.imports':

HandlerActivation(commandId=org.eclipse.jdt.ui.edit.text.java.organize.imports,
handler=com.plugin.generator.wizard.AdGenaratorWizard$1@2b8e2b8e,expression=,sourcePriority=0) 

HandlerActivation(commandId=org.eclipse.jdt.ui.edit.text.java.organize.imports,
handler=com.plugin.generator.wizard.AdGenaratorWizard$1@25f025f0,expression=,sourcePriority=0)

If you try to understand what exactly happens, supposing you would like to do a manual Organize Imports using "Ctrl+Shift+O", sometimes eclipse would prompt you with a window asking for selecting import statements to choose among similar packages. 如果您试图了解究竟发生了什么,假设您想要使用“Ctrl + Shift + O”进行手动组织导入,有时eclipse会提示您一个窗口,要求选择导入语句以在类似的包中进行选择。 (For eg: Choose either "org.eclipse.ui.commands" OR "org.eclipse.core.commands") Now thats why the above said error message occurs. (例如:选择“org.eclipse.ui.commands”或“org.eclipse.core.commands”)这就是为什么会出现上述错误消息的原因。

When I try to run organize imports automatically through my code, it gets into a conflict of which import to choose and returns exception. 当我尝试通过我的代码自动运行组织导入时,它会进入选择导入的冲突并返回异常。

So is there any way to handle that? 那么有什么方法可以解决这个问题吗? Hope u understand what exactly happens. 希望你明白究竟发生了什么。 Please suggest how I can do that. 请建议我如何做到这一点。

I was on this for about a week and finally got it working... :) 我在这上面大约一个星期,终于让它工作了...... :)

try {
final IWorkbenchPartSite targetSite = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService()
.getActivePart().getSite();

    if(targetSite!=null){ 
    System.out.println("TargetSite obtained");
    organizeImports(wiProject, targetSite);
    }

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 



public void organizeImports(final IProject project, final IWorkbenchSite targetSite) throws CoreException {
Runnable job = new Runnable() {

@Override
public void run() {
    OrganizeImportsAction org = new OrganizeImportsAction(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.getShell().getDisplay().syncExec(job);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM