I'm learning Java's bytecode by read the Java Virtual Machine Specification
I'm confused about the LocalVariableTable attribute, which official document says when executing a .class file, all slots of LocalVariableTable may be reused.
I cannot write any code compiled like this:
sipush xxx
istore_0
.....
dup
astore_0
Can anyone give me some examples?
There is no “java's assembly language” so you can not compile a pseudo assembly code with the tools provided by the JDK. You can only use the other direction, print the bytecode of a compiled class with javap
.
There are 3rd party tools providing an assembly language for the JVM, e.g. Krakatau, but neither is part of a standard. Most of those languages will look similar or even offer compatibility with other tools though, as they use the same mnemonics from the JVM specification and the output format of javap
as a starting point.
Reusing variable slots is a trivial thing. It happens all the time when local variables have disjunct scopes. E.g.
import java.util.spi.ToolProvider;
public class ReusedVariableSlots {
static class Example {
public static void exampleMethod() {
{ short s = 1234; }
{ Object o = null; }
}
private Example() {}
}
public static void main(String... arg) {
ToolProvider.findFirst("javap").ifPresentOrElse(
javap ->javap.run(System.out, System.err, "-c", Example.class.getName()),
() -> System.out.println("javap not found"));
}
}
will print something like
Compiled from "ReusedVariableSlots.java"
class ReusedVariableSlots$Example {
public static void exampleMethod();
Code:
0: sipush 1234
3: istore_0
4: aconst_null
5: astore_0
6: return
}