How to find the source for a class file

Suppose all I have is the full path for a '.class' file, and I need to get hold of the VirtualFile that references the source for this class file. What's the easiest way to do this?

0
3 comments
Avatar
Permanently deleted user

Oh, if it wasn't clear, the '.class' file is guaranteed to be compiled from the current project sources -- so chances are it's sources are part of the current project.

0
Avatar
Permanently deleted user

Marcus,

you could start from this code, that returns the source file from a
class FQN


public static VirtualFile fqnToSourceFile (Project i_project,
String i_class)
{
String fqn = i_class.endsWith (".java")
? i_class.replaceFirst (".java", "")
: i_class;

GlobalSearchScope scope = GlobalSearchScope.allScope (i_project);
PsiClass psiClass = PsiManager.getInstance (i_project).findClass
(fqn, scope);
if (null == psiClass) {
return null;
}

PsiElement psiClassSource = psiClass.getNavigationElement ();
// to avoid viewing the decompiled class
PsiFile psiFile = psiClassSource.getContainingFile ();

return psiFile.getVirtualFile ();
}


Alain

0
Avatar
Permanently deleted user

Many thanks, Alain. I just had to do some massaging to figure out the FQN from the file path, and everything worked fine.

0

Please sign in to leave a comment.