tableswitch : jump according to a table : index : visitTableSwitchInsn()
int val = pop(); // pop an int from the stack
if (val < low || val > high) { // if its less than <low> or greater than <high>,
pc += default; // branch to default
} else { // otherwise
pc += table[val - low]; // branch to entry in table
}
Notice
that all addresses stored in the table are relative to the address of the
tableswitch opcode in the bytecode. If you are using Jasmin, these
addresses are computed for you from the address of the given labels.
iload_1 ; push local variable 1 onto the stack
; if the variable contains 0, jump to ZeroLabel
; if the variable contains 1, jump to OneLabel
; if the variable contains 2, jump to TwoLabel
; otherwis jump to DefaultLabel
tableswitch 0 2
ZeroLabel
OneLabel
TwoLabel
default: DefaultLabel
ZeroLabel:
; the variable contained 0 ...
ldc 100
ireturn ; return the result 100
OneLabel:
; the variable contained 1 ...
bipush 200
ireturn ; return the result 200
TwoLabel:
; the variable contained 2 ...
bipush 300
ireturn ; return the result 300
DefaultLabel:
; the variable contained something else ...
bipush 0
ireturn ; return the result 0
| Before | After |
| val | ... |
| ... | ... |
| Type | Description |
| u1 | tableswitch opcode = 0xAA (170) |
| - | ...0-3 bytes of padding ... |
| s4 | default_offset |
| s4 | <low> |
| s4 | <low> + N - 1 |
| s4 | offset_1 |
| s4 | offset_2 |
| ... | ... |
| s4 | offset_N |