Eclipse creates CompilationUnit from .java file

How to load .java file in CompilationUnit? For example, let's say I have an A.java file in my current project. I would like to upload it to CompilationUnit and then pass it to ASTParser. It is not an option to simply load it as plain text, as it seems that in this case I will not get the binding information in AST.

+5
source share
1 answer

You can upload projects using the jdtand libraries eclipse core.

Using the following code, you can download all 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, 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 to get CompilationUnit

ASTParser parser = ASTParser.newParser(AST.JLS3); 
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(unit);
parser.setResolveBindings(true);
CompilationUnit cUnit = parser.createAST(null);

CompilationUnit ASTParser.

+9

All Articles