2014-08-27 67 views
1

假設我有一個類名稱,如源文件: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-插件」(容易,也許更健壯)打開給定類的源文件的方式。

回答

0

我能做到這一點是這樣的:

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; 
    }