## Wednesday, October 31, 2012

### Eclipse CompilationUnit

Eclipse uses compilation unit to represent a class. It's reasonable considering one java source generates one class file with the same name (if we forget about the inner class).

One can think of compilation unit in eclipse as a ASTNode for java code as it subclassing ASTNode.

Getting Compilation is a little bit complicated.
• One needs to create a parser as parser has a reference to it. Call parser.createAST() to get CompilationUnit. Don't forget to down casting it to CompilationUnit.
• One needs to setup a parser with the source of ICompilationUnit
And this is the code.
// … lwType is IType object
org.eclipse.jdt.core.ICompilationUnit lwCompilationUnit = lwType.getCompilationUnit();
// create parser and set it up
final ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(lwCompilationUnit);
parser.setResolveBindings(true); // we need bindings later on
// can get CompilationUnit from parser
CompilationUnit unit = (CompilationUnit) parser.createAST(null /* IProgressMonitor */);