IntellijIdea插件开发:在文本编辑器中导航到给定类的源文件



假设我有一个类似于的类名

org.myPackage.MyClass

我想在文本编辑器中导航到该类的源文件。到目前为止,我知道如何在编辑器中打开文件:

FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
VirtualFile vf = LocalFileSystem.getInstance().findFileByPath(myPath);
fileEditorManager.openFile(vf, true, true);

我也知道如何获得模块的源根,所以到目前为止我正在做的是将myPath设置为类似于:

myPath = mainModuleSourceRoot + substituteDotsForSlash("org.myPackage.MyClass")

然而,我想知道是否有一种更"面向IntellijIdea插件"(更简单,也许更健壮)的方式来打开给定类的源文件。

我可以这样做:

    GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    PsiClass psiClass = JavaPsiFacade.getInstance(project).findClass("org.myPackage.MyClass", scope);
    if ( psiClass != null ) {
        FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
        fileEditorManager.openFile(psiClass.getContainingFile().getVirtualFile(), true, true);
    } else {
        //handle the class not found
    }

在这里找到答案:https://code.google.com/p/ide-examples/wiki/IntelliJIdeaPsiCookbook#Find_a_Class


编辑的答案

我终于做了这样的事:

    GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    PsiClass psiClass = JavaPsiFacade.getInstance(project).findClass(className, scope);
    if (psiClass != null) {
        FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
        //Open the file containing the class
        VirtualFile vf = psiClass.getContainingFile().getVirtualFile();
        //Jump there
        new OpenFileDescriptor(project, vf, 1, 0).navigateInEditor(project, false);
    } else {
        //Handle file not found here....
        return;
    }

最新更新