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?
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:
As mentioned in a comment use your own traversal of existing classes, or
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:
-datacommand line argument.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 typeJUnit Plug-in Testand on tabMainselectRun an application: [No Application] - Headless Mode.