How to programmatically find a java file in eclipse from full classname?

后端 未结 3 1537
温柔的废话
温柔的废话 2020-12-19 18:22

Inside an eclipse plugin, I\'d like to open a file in editor. I know the full package and class name, how can I determine the path of the java file from this?

3条回答
  •  旧时难觅i
    2020-12-19 19:13

    I know this is a bit old but I had the same need and I had a look at how eclipse does it for stack trace elements (they have a hyperlink on them). The code is in org.eclipse.jdt.internal.debug.ui.console.JavaStackTraceHyperlink (the link is "lazy" so the editor to open is resolved only when you click on it).

    What it does is it first searches for the type in the context of the launched application, then for in the whole workspace (method startSourceSearch) :

    IType result = OpenTypeAction.findTypeInWorkspace(typeName, false);
    

    And then opens the associated editor (method processSearchResult, source is the type retrieved above) :

    protected void processSearchResult(Object source, String typeName, int lineNumber) {
        IDebugModelPresentation presentation = JDIDebugUIPlugin.getDefault().getModelPresentation();
        IEditorInput editorInput = presentation.getEditorInput(source);
        if (editorInput != null) {
            String editorId = presentation.getEditorId(editorInput, source);
            if (editorId != null) {
                try { 
                    IEditorPart editorPart = JDIDebugUIPlugin.getActivePage().openEditor(editorInput, editorId);
                    if (editorPart instanceof ITextEditor && lineNumber >= 0) {
                        ITextEditor textEditor = (ITextEditor)editorPart;
                        IDocumentProvider provider = textEditor.getDocumentProvider();
                        provider.connect(editorInput);
                        IDocument document = provider.getDocument(editorInput);
                        try {
                            IRegion line = document.getLineInformation(lineNumber);
                            textEditor.selectAndReveal(line.getOffset(), line.getLength());
                        } catch (BadLocationException e) {
                            MessageDialog.openInformation(JDIDebugUIPlugin.getActiveWorkbenchShell(), ConsoleMessages.JavaStackTraceHyperlink_0, NLS.bind("{0}{1}{2}", new String[] {(lineNumber+1)+"", ConsoleMessages.JavaStackTraceHyperlink_1, typeName}));  //$NON-NLS-2$ //$NON-NLS-1$
                        }
                        provider.disconnect(editorInput);
                    }
                } catch (CoreException e) {
                    JDIDebugUIPlugin.statusDialog(e.getStatus()); 
                }
            }
        }       
    }
    

    Code has copyright from eclipse. Hopfully I'm allowed to reproduced it if this is mentionned.

提交回复
热议问题