Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically generate .class files?

I would like to write a compiler for a toy-language for Java. I would like to generate runnable .class files. I was wondering what is the best library or tool available for doing this? I know I could learn the binary format for all the instructions and build my own constant pool etc, but that seems like work that ought to have been already done: no point reinventing the wheel, right?

Searching online I've found two different Java Assembly languages, Jasmin and Jamaica, however only Jasmin looks somewhat maintained.

Is there a Java library for writing byte codes to a stream? Is this what the Apache BCEL is?

Is their a tool for this that is the "standard" for byte-code generation, like Antlr is for parsing?


PS- The toy language is Brainf***, I wanted something where I could have a simple "grammar" so I could focus on the generation aspect and not the parsing part... that will come later on the next step.

like image 925
Sled Avatar asked Nov 19 '11 16:11

Sled


People also ask

How does the .class file get generated?

class" file is created as a result of successful compilation by the Java compiler from the ". java" file. Each class in the . java file is compiled into a separate class file if the ".

How do I create a .class file?

To create a new Java class or type, follow these steps: In the Project window, right-click a Java file or folder, and select New > Java Class. Alternatively, select a Java file or folder in the Project window, or click in a Java file in the Code Editor. Then select File > New > Java Class.

How do I create a .class file in Java project?

File > New > Class After clicking class above, a new dialog box opens up. It is the wizard to create new Java class in Eclipse.

Are .class files generated?

Answer-> A class file generated when the compiler starts the compilation and exactly at that time a interpreter(JRE) generates class file.


2 Answers

ASM and BCEL do basically similar things. I'd recommend ASM as it's much more supported, much smaller, and is up to date JDK-wise.

like image 150
MeBigFatGuy Avatar answered Sep 19 '22 11:09

MeBigFatGuy


It sounds like you're looking for Apache BCEL:

The Byte Code Engineering Library (Apache Commons BCEL™) is intended to give users a convenient way to analyze, create, and manipulate (binary) Java class files (those ending with .class).

like image 30
Jon Skeet Avatar answered Sep 18 '22 11:09

Jon Skeet