Get source code of PsiClass of library/dependency

Hello,

I am developing a plugin which needs to read the source code of e.g. a Java class from a library.

The PsiClass is retrieved from a PsiElement of a currently open editor:
 

val psiClass = PsiTypesUtil.getPsiClass(psiElement.type)
if (psiClass != null) {
                val file = psiClass.navigationElement.containingFile.virtualFile
                val module = ModuleUtilCore.findModuleForPsiElement(psiElement)
                val moduleRootManager = ModuleRootManager.getInstance(module!!)
                if (file.isInLocalFileSystem) {
                     // file in local project, can simply be read with file.readText()
                    return file
                } else {
                     // file from Library (or SDK, but they should be ignored), for e.g. a Java class this is the compiled class file inside the dependency JAR
                    // TODO: how to retrieve the source code (if the library provides sources)?
                }
            }

I know that the libraries source URLs can supposedely be accessed with:

val module = ModuleUtilCore.findModuleForPsiElement(psiElement)
val moduleRootManager = ModuleRootManager.getInstance(module!!)
val orderEntries = ModuleRootManager.getInstance(module).orderEntries
orderEntries[0].getUrls(OrderRootType.SOURCES)

But that just gives me a list of all library sources, how do I determine the correct one and get the correct Class file? Also how do I read the text e.g. from inside a JAR? The implementation should not be Language specific to Java.

 

Thank you.

1

Please sign in to leave a comment.