Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which library/program can be used to generate Java-bytecode? [closed]

Tags:

java

jvm

bytecode

I know about BCEL, but this project seems to be dead, as it had no releases for two years. And the Java-world moves on. For example JDK 1.6 has a new class-file-format.

So what library can be used to create bytecode for the JVM. If no library, a program is ok too, if I can manipulate the generated code in detail, for example a bytecode-assembler.

Which software can you recommend? Is it easy too use? has good examples/tutorials?

EDIT: For all asking: Yes, the javac is fine. But for generating some classes at runtime, a path directly to bytecode would be cleaner.

like image 944
Mnementh Avatar asked Nov 14 '08 21:11

Mnementh


People also ask

What generates byte code in Java?

How is Byte Code generated? Compiler converts the source code or the Java program into the Byte Code(or machine code), and secondly, the Interpreter executes the byte code on the system. The Interpreter can also be called JVM(Java Virtual Machine).

Is bytecode generated by Java compiler?

When a Java program is executed, the compiler compiles that piece of code and a Bytecode is generated for each method in that program in the form of a . class file. We can run this bytecode on any other platform as well. But the bytecode is a non-runnable code that requires or relies on an interpreter.

How is Java bytecode stored?

The bytecodes streams are stored in the method area of the JVM. The bytecodes for a method are executed when that method is invoked during the course of running the program. They can be executed by intepretation, just-in-time compiling, or any other technique that was chosen by the designer of a particular JVM.


1 Answers

ASM

http://asm.objectweb.org/

It is much faster than BCEL and supports generics and annotations. One point about its architecture: in order to ensure high performance ASM is built around a parser that throws events (in contrast to BCEL where the parser builds a data structure). This is somewhat similar to the difference between SAX and DOM parsers. It takes some practice to get used to this kind of thinking.

EDIT (Following McDowell's comment): Indeed visitors are heavily used in ASM, but it's more than plain visitors: the visited data structure is lazily built by the parser, so if you're not interested in certain parts of the classfile (for example, you want to know the names of the methods but you don't care about their body), you can return a null from the visitMethod() method. This will make the parser skip the method body sections thereby preventing the (expensive) construction of the net of objects fully describing the method.

like image 123
Itay Maman Avatar answered Oct 21 '22 15:10

Itay Maman