What is the best way to get the project packages?

Is there a way to quickly get the list of java root packages in the source folders of the project?

com.arcbees.project
com.arcbees.test

Thanks,
Brandon

2 comments

What I found to get the top level pacakges.

https://code.google.com/p/ide-examples/wiki/IntelliJIdeaPsiCookbook

private List<PsiPackage> getPackages() {
    Project myProject = presenterConfigModel.getProject();
    ProjectViewSettings viewSettings = new ProjectViewSettings();

    final List<VirtualFile> sourceRoots = new ArrayList<VirtualFile>();
    final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(myProject);
    ContainerUtil.addAll(sourceRoots, projectRootManager.getContentSourceRoots());

    final PsiManager psiManager = PsiManager.getInstance(myProject);
    final List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>();
    final Set<PsiPackage> topLevelPackages = new HashSet<PsiPackage>();

    for (final VirtualFile root : sourceRoots) {
        final PsiDirectory directory = psiManager.findDirectory(root);
        if (directory == null) {
            continue;
        }
        final PsiPackage directoryPackage = JavaDirectoryService.getInstance().getPackage(directory);
        if (directoryPackage == null || PackageUtil.isPackageDefault(directoryPackage)) {
            // add subpackages
            final PsiDirectory[] subdirectories = directory.getSubdirectories();
            for (PsiDirectory subdirectory : subdirectories) {
                final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(subdirectory);
                if (aPackage != null && !PackageUtil.isPackageDefault(aPackage)) {
                    topLevelPackages.add(aPackage);
                }
            }
            // add non-dir items
            children.addAll(ProjectViewDirectoryHelper.getInstance(myProject).getDirectoryChildren(directory, viewSettings, false));
        } else {
            // this is the case when a source root has package prefix assigned
            topLevelPackages.add(directoryPackage);
        }
    }

    return new ArrayList<PsiPackage>(topLevelPackages);
}

0

You should be able to use the JavaPsiFacade to do what you want. Try:

PsiPackage pack = JavaPsiFacade.getInstance(project).findPackage(qualifiedName);

If you want the root package you can use findPackage(""). Once you have a package you can use .getSubPackages() on it and iterate from there.

0

Please sign in to leave a comment.