How can I load a .java file into a CompilationUnit? For example, lets say I have a A.java file in my current project. I would like to load it into a CompilationUnit and then pass it to the ASTParser. It is not an option just to load it as a plain text since it seems that in that case I will not get the binding information in the AST.
Asked
Active
Viewed 5,349 times
1 Answers
9
You can load the projects using jdt
and eclipse core
libraries.
Using the following code you can load all the projects in the workspace.
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
// Get all projects in the workspace
IProject[] projects = root.getProjects();
Then you can get packages and in turn the java files.
IPackageFragment[] packages = JavaCore.create(project).getPackageFragments();
IPackageFragment mypackage = packages.get(0); // implement your own logic to select package
ICompilationUnit unit = mypackage.getCompilationUnits();
Then you can use this ICompilationUnit object for getting the CompilationUnit
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(unit);
parser.setResolveBindings(true);
CompilationUnit cUnit = parser.createAST(null);
This CompilationUnit object can be passed on to the ASTParser.

Unni Kris
- 3,081
- 4
- 35
- 57
-
This will work only for Eclipse projects? I.e., it will not work for Java projects? – zpavlinovic Jun 24 '12 at 05:28
-
You cannot use JDT in java projects by having jar files. To use JDT, you need to have the program running as a plug-in (or at least, an OSGi-enabled application). – Unni Kris Jun 24 '12 at 07:29
-
Ok, so I can load the .java file to CompilationUnit by this approach only for eclipse projects. FYI, it is possible to use JDT outside of the eclipse projects by using setSource(char[]) and setEnvironment methods. (from version 3.6) – zpavlinovic Jun 24 '12 at 18:16
-
@bellpeace well i am using ver 3.5.1 . Its nice to know the JDT team have included the support outside eclipse env in their new version. May be i will try it out. Thanks for the info anyway. – Unni Kris Jun 25 '12 at 04:38
-
@prosseek you can loop through the `packages` [IPackageFragment array] and get the package. mypackage is of Type `IPackageFragment`. – Unni Kris Nov 01 '12 at 06:57
-
You can use the Eclipse JDT Language Server to enable code assistant features, without having to setup an Eclipse project manually: https://stackoverflow.com/a/71015645/1925327 – moritz.vieli Feb 07 '22 at 08:49