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.
Eclipse create CompilationUnit from .java file
Asked Answered
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.
This will work only for Eclipse projects? I.e., it will not work for Java projects? –
Thermochemistry
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). –
Senator
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) –
Thermochemistry
@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. –
Senator
@prosseek you can loop through the
packages
[IPackageFragment array] and get the package. mypackage is of Type IPackageFragment
. –
Senator You can use the Eclipse JDT Language Server to enable code assistant features, without having to setup an Eclipse project manually: https://mcmap.net/q/1816239/-eclipse-jdt-how-to-get-data-model-for-java-content-assist –
Flaming
© 2022 - 2024 — McMap. All rights reserved.