How can I get only package that I declared in a project?

Answered

I am trying to get PsiPackage variable in a Project project variable.

 

I already know how to get all the packages in a project.

 

But, if code is like below, I only want PsiPackage of "package com.SoftwareMatrix" (Not imported, user defined package)

 

package com.SoftwareMatrix;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiPackage;
import com.intellij.ui.content.Content;

But if I get all packages and print that, the below is printed.

 

PsiPackage:com.thaiopensource
PsiPackage:com.google
PsiPackage:com.github
PsiPackage:com.trilead
PsiPackage:com.android
PsiPackage:com.twelvemonkeys
PsiPackage:com.petebevin
PsiPackage:com.intellij
PsiPackage:com.SoftwareMatrix    <- I only want this

 

is there any way to get only the package that I declare?

0
2 comments

com.intellij.psi.PsiJavaFile#getPackageName

0
Avatar
Permanently deleted user

Thanks! I will share my solution I found. Given argument Project project, this code finds packages in that project

 

Set<PsiPackage> ret = new HashSet<PsiPackage>();

Collection<VirtualFile> virtualFiles =
FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, JavaFileType.INSTANCE,
GlobalSearchScope.projectScope(project));
// Get only java files which is contained by PROJECT


for (VirtualFile vf: virtualFiles) {
PsiFile psifile = PsiManager.getInstance(project).findFile(vf);

if (psifile instanceof PsiJavaFile) {
PsiJavaFile psiJavaFile = (PsiJavaFile) psifile;
String PackageName = psiJavaFile.getPackageName();
PsiPackage pack = JavaPsiFacade.getInstance(project).findPackage(PackageName);
ret.add(pack);
}
}
1

Please sign in to leave a comment.