Use JDT to extract IcompilationUnits in a standalone Java application

381 Views Asked by At

I am writting an ordinary Java application and want to extract all ICompilationUnit of an input project (which is not necessary developed by Eclipse). As I am not developing an Eclipse plugin, I can't use the below code to extract ICompilationUnit:

IWorkspace workspace = ResourcesPlugin.getWorkspace();
IPath path = Path.fromOSString(source.getAbsolutePath());
IFile file = workspace.getRoot().getFileForLocation(path);
ICompilationUnit compilationUnit = (ICompilationUnit) JavaCore.create(file);

Currently, I am using the below code to parse the input Java file. (str contains the source code of input java file)

ASTParser parser = ASTParser.newParser(AST.JLS12);
parser.setSource(str.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
CompilationUnit cu = (CompilationUnit) parser.createAST(null);

However, the below code return null as it was not created from a Java element.

ICompilationUnit icu = (ICompilationUnit)compilationUnit.getJavaElement();

Question: Is there any way to extract ICompilationUnits in an ordinary Java Application?

1

There are 1 best solutions below

2
Stephan Herrmann On

The JDT search engine needs an index. Within the IDE the index is created during workspace build. This means without a workspace there is no out-of-the-box approach to using the search engine.

It may in theory be possible to implement your own index, but that can definitely not be recommended.

Two options remain:

  1. As mentioned in a comment use your own traversal of existing classes, or

  2. Let your application initialize a workspace behind the scenes into which your code is imported as real Java projects. After a build of that workbench, the search engine should be available. All this could happen in a headless application with no need to fire up the Eclipse UI.

For inspirations regarding option (2) you could start here:

  • PDE's CoreTestApplication, which is the headless application used, e.g., for running JDT's own tests. A workspace is automatically available in the locations passed using the -data command line argument.
  • JDT's AbstractJavaModelTests, which provides tons of utilities for programmatically creating & configuring Java projects.
  • Subclasses of AbstractJavaModelTests which have gazillions of examples how those Java projects are used, including search.

If you want to see it all live, I suggest you set up a workspace with JDT and PDE projects in source. The easiest way would be to use Oomph for this.

The above CoreTestApplication will be run, if you select any test class, invoke Run as > Run configurations... then create a launch configuration of type JUnit Plug-in Test and on tab Main select Run an application: [No Application] - Headless Mode.