What is Bytecode
suggest changeBytecode is the set of instructions used by the JVM. To illustrate this let’s take this Hello World program.
public static void main(String[] args){
System.out.println("Hello World");
}
This is what it turns into when compiled into bytecode.
public static void main(java.lang.String[]);
Code:
0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3 // String Hello World
5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
What’s the logic behind this?
getstatic - Retrieves the value of a static field of a class. In this case, the PrintStream out of System.
ldc - Pushes a constant onto the stack. In this case, the String “Hello World”.
invokevirtual - Invokes an instance method. The object reference and the method arguments are taken from the stack. println returns void, so it does not push a result.
Well, there has to be more right?
An opcode is one byte, so there are 256 possible values (0–255), but not every value is assigned. A table of the defined opcodes can be found here: Java bytecode instruction listings.
How can I write / edit bytecode?
There are multiple ways to write and edit bytecode. You can use a compiler, use a library, or use a program.
For writing:
For editing:
- Libraries
- ASM
- Javassist
- BCEL - Doesn’t support Java 8+
- Tools
- Bytecode-Viewer
- JBytedit
- reJ - Doesn’t support Java 8+
- JBE - Doesn’t support Java 8+
I’d like to learn more about bytecode!
There’s probably a specific documentation page specifically for bytecode. This page focuses on the modification of bytecode using different libraries and tools.