we're writing some sort of compiler from Pascal to JVM Bytecode. And we've already implemented an expression tree generation, so the next step should be the creation of .class
file. Can you suggest any guide/tutorial of how to generate any .class
file at least from some static data? Because I've googled for 2 hours already and read JVM specification, but I really need some even simplest example to start developing the whole stuff.
问题:
回答1:
Someone has already written a widely-used byte code generation library: CGLIB.
You'd have it knocked if you could figure out how to get your AST into CGLIB.
回答2:
Actually there is an example file inside ASM folder that you download. It's called Helloworld and it's located in examples
subfolder. It shows how to compile (generate from scratch) .class
file that corresponds to simple hello world app. It also shows how to get date from .class
files but it's another story.
Maybe this is'n the best way, but when you need to start with java byte code generation and you need some basic examples it's a good idea to have a look at ASM and the examples that are bundled within standard package.
Moreover Groovy uses ASM to generate its code :)
回答3:
I don't know if you are aware, but there is a backend for the FPC that generates bytecode compliant to the JDK 1.5. The development looks fairly recent (November 2011). You should have a look at it.
回答4:
There are a couple of widely-used bytecode generation projects.
ASM and CGLib are probably the two best examples.
You probably don't want to build a generation library for yourself from scratch - it's a lot of work, difficult to get right and probably doesn't offer you much over using an existing project.
ASM is widely used by non-Java languages on the JVM, has OK-ish documentation and is not too bad to get going.
I haven't used CGLib as much, but I didn't find it as easy to get started with.
As a final data point, the Java 8 team are prototyping some of the new Java features (including lambda expressions) with ASM.