Wednesday, October 31, 2012

Eclipse CompilationUnit

Screen Shot 2012 10 31 at 9 02 43 AM
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. Screen Shot 2012 10 31 at 9 13 20 AM

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 */);

References

No comments:

Post a Comment