Tapping the Java compiler (javac)

Since parts of Java are Open Source, e.g. the Java compiler (javac), you can tap this home-made SUN tool to traverse the abstract syntax tree of any Java file by your own Visitor. Firstly, here are the code snippets for the tapping:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// setup Context and FileManager
Context context = new Context();
JavacFileManager.preRegister(context);
 
// obtain FileManager and FileObject
JavacFileManager fileManager =
  (JavacFileManager)context.get(JavaFileManager.class);
JavaFileObject fileObject =
  fileManager.getFileForInput("samples/HelloWorld.java");
 
// create Scanner and Parser as soon as visit AST via MyVisitor
Scanner scanner = Scanner.Factory.instance(context)
  .newScanner(fileObject.getCharContent(false));
Parser parser = Parser.Factory.instance(context)
  .newParser(scanner, true, true);
parser.compilationUnit().accept(new MyVisitor());

And secondly here come the snippets for building your own visitor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class MyVisitor extends Visitor {
  // visits the Top-Level-Element
  public void visitTopLevel(JCCompilationUnit that) {
    List list = that.getTypeDecls();
    for ( JCTree typeDecl : list ) {
      typeDecl.accept(this);
    }
  }
 
  // visits the class definitions
  public void visitClassDef(JCClassDecl that) {
    System.out.println("Class = " + that.getSimpleName());
    for ( JCTree member : that.getMembers() ) {
      member.accept(this);
    }
  }
 
  // visits the method definitions
  public void visitMethodDef(JCMethodDecl that) {
    System.out.println("Method = " + that.getName());
    for ( JCVariableDecl param : that.getParameters() ) {
      System.out.println("Parameter = " + param.getName());
    }
  }
 
  // Are you looking for more overridings?
  // Have a look at the members of class Visitor!
}

All you have to do to is download and build the javac sources from www.java.net. Use the enclosed ANT script (build.xml) and you’ll get a jar-file (javac.jar). Just integrate it in your javac build path before compiling your program.

0 Responses to “Tapping the Java compiler (javac)”


  • No Comments

Leave a Reply