我目前正在学习Java字节码,但陷入了困境。
可以说我有一个包含整数currentPos的超类。
我生成了一个方法,该方法必须生成一个子类并递增currentPos,但不知何故它引发了堆栈下溢错误。
这是我的代码:
runMethod.instructions.add(new FieldInsnNode(GETFIELD, "me/looka/bfc/FooSuperClass", "currentPos", "I"));
runMethod.instructions.add(new InsnNode(ICONST_1));
runMethod.instructions.add(new InsnNode(IADD));
runMethod.instructions.add(new FieldInsnNode(PUTFIELD, "me/looka/bfc/FooSuperClass", "currentPos", "I"));
通过以下步骤,这应该使currentPos正确递增:
将当前值放入堆栈
将值1加到堆栈中
将两个添加的值加在一起,将这两个值弹出堆栈,然后将添加的值压入。
使用堆栈的当前值设置字段
弹出那个附加值
最佳答案
getfield
/ putfield
用于非静态字段。如果该字段是静态的,则需要getstatic
/ putstatic
。否则,您需要提供对象以引用其中的字段。假设该对象位于本地插槽0(通常保留此参数)中,则需要
runMethod.instructions.add(new VarInsnNode(ALOAD, 0));
runMethod.instructions.add(new VarInsnNode(ALOAD, 0));
runMethod.instructions.add(new FieldInsnNode(GETFIELD, "me/looka/bfc/FooSuperClass", "currentPos", "I"));
runMethod.instructions.add(new InsnNode(ICONST_1));
runMethod.instructions.add(new InsnNode(IADD));
runMethod.instructions.add(new FieldInsnNode(PUTFIELD, "me/looka/bfc/FooSuperClass", "currentPos", "I"));