I need to access a variable in bytecode. I have figured out how to do this with local variables (using ILOAD), but I can't seem to get it to work with values that are outside of the method I am working in. Is there an Opcode that loads a variable inside of a class but outide of a method?
This works when the variable is inside of the method:
if (currentNode.getOpcode() == RETURN)
{
InsnList toInject = new InsnList();
toInject.add(new TypeInsnNode(NEW, "timeTraveler/mechanics/LivingPlaceBlockEvent"));
toInject.add(new InsnNode(DUP));
toInject.add(new VarInsnNode(ALOAD, 5));
toInject.add(new VarInsnNode(ALOAD, 6));
toInject.add(new VarInsnNode(ILOAD, 2));
toInject.add(new VarInsnNode(ILOAD, 3));
toInject.add(new VarInsnNode(ILOAD, 4));
toInject.add(new MethodInsnNode(INVOKESPECIAL, "timeTraveler/mechanics/LivingPlaceBlockEvent", "<init>", "(Lnet/minecraft/entity/EntityLivingBase;Lnet/minecraft/item/ItemStack;III)V"));
toInject.add(new VarInsnNode(ASTORE, 7));
toInject.add(new FieldInsnNode(GETSTATIC, "net/minecraftforge/common/MinecraftForge", "EVENT_BUS", "Lnet/minecraftforge/event/EventBus;"));
toInject.add(new VarInsnNode(ALOAD, 7));
toInject.add(new MethodInsnNode(INVOKEVIRTUAL, "net/minecraftforge/event/EventBus", "post", "(Lnet/minecraftforge/event/Event;)Z"));
toInject.add(new InsnNode(POP));
m.instructions.insertBefore(currentNode, toInject);
}
Variables defined inside a class are called fields. To access them, you use the getfield
or getstatic
instructions, depending on whether the field is static or not.
Public static fields are the closest Java has to global variables.