Take the 2-minute tour ×

This page describes how I can use the code generator in javac to generate code given that I can build an AST (using a separate parser which I wrote). The technique involves editing javac's source code to basically bypass the Java parser, so that one could supply his/her own AST to the code generator. This could work, but I was hoping to do it in a slightly cleaner way. I want to include the code generating part of javac as a library in my project so I can use it to generate code, without bringing with it the rest of javac's source.

Is there a way to do this with javac, or is there perhaps a better library?

Also, feel free to change the question's title. I couldn't think of a better one, but it's a little ambiguous. If you suggest an edit for a better title, I'll accept it.

share|improve this question
Is this your own AST, a common intermediate AST, or the AST already used by javac? (That part is not readily apparent to me.) –  user166390 Jul 26 '12 at 20:35
My own AST. I'm generating it with a parser I wrote. (Sorry for the ambiguity) –  Hassan Jul 26 '12 at 20:36
If it is your own AST, you'll first have to translate to the AST form used by javac. –  Ira Baxter Jul 26 '12 at 21:09
@IraBaxter Yeah, but that shouldn't be too difficult. I have my own AST classes that are very similar to the ones that javac uses, so switching to javac's will be manageable. –  Hassan Jul 26 '12 at 21:45
add comment

1 Answer

up vote 3 down vote accepted

I think what you might be interested in is a java library like BCEL(ByteCode Engineering Library)

I played around with it back when I took a class on compiler construction, basically, it has a nice wrapper for generating the constant pool, inserting named bytecode instructions into a method and whatnot, then when you are done, you can either load the class at runtime with a custom classloader, or write it out to a file in the normal way.

With BCEL, it should be relatively easy to go from the syntax tree to the java bytecodes, albeit a bit tedious, but you may want to just use BCEL to generate the raw bytecode without building the tree as well in some cases.

share|improve this answer
I will certainly look into BCEL. Javac's source is kind of messy anyway. –  Hassan Aug 1 '12 at 19:49
add comment

Your Answer


