Find and run main classes programatically

Answered

Hello everyone,

I need to find programatically all main classes in my project.
My project contains multiple server configurations and I am developing a plugin to add actions to the popup menus to start these servers.
A server is started via it's main method. Each server imports a BaseServer class to execute a static method call on it.

Currently, I am collecting all possible servers with the following:

  Collection<VirtualFile> files = FileTypeIndex.getFiles (JavaFileType.INSTANCE, getSearchScope (module));

PsiManager manager = PsiManager.getInstance (module.getProject ());
return files.stream ()
.filter (f -> !f.isDirectory ())
.map (manager::findFile)
.filter (Objects::nonNull)
.filter (this::importsBaseServer)
.toList ();

I.e. I am traversing each Java file (>500), and check on each import statement if the base class is being imported.

However, that seems very inefficient and results in UI freezes of multiple seconds.
I wondered if there is any better solution to find only the executable Java files?

I found 

JavaExecutionUtil.findMainClass ()

however, the server names differ so I cannot provide a classname for this method.

0
2 comments
  1. Locate the static main PsiMethod from the BaseServer class (https://plugins.jetbrains.com/docs/intellij/psi-cookbook.html#how-do-i-find-a-class-by-qualified-name then PsiClass#findMethod)
  2. use com.intellij.psi.search.searches.ReferencesSearch to locate all callers passing in desired usage scope
1

Works perfectly, thanks!

0

Please sign in to leave a comment.