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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With