Home > database >  How to add an integer to a constant in Java ASM bytecode?
How to add an integer to a constant in Java ASM bytecode?

Time:12-27

I am trying to add an integer variable x to a static int variable named count using java ASM.

After a lot of searching, I found a way to add a fixed integer to a static int variable

                InsnList numCounting = new InsnList();

                // insert count  
                numCounting.add(new FieldInsnNode(Opcodes.GETSTATIC, classNode_c.name, "count", "I"));
                numCounting.add(new InsnNode(Opcodes.ICONST_1));
                numCounting.add(new InsnNode(Opcodes.IADD));
                numCounting.add(new FieldInsnNode(Opcodes.PUTSTATIC, classNode_c.name, "count", "I"));    
                mn.instructions.insert(node, numCounting);

How do I generalize this such that I can add an arbitrary int to count? Thanks

CodePudding user response:

I can't really test this code right now, but this should work

            InsnList numCounting = new InsnList();

            // insert count  
            numCounting.add(new FieldInsnNode(Opcodes.GETSTATIC, classNode_c.name, "count", "I"));
            numCounting.add(new LdcInsnNode( x )); // Load a constant onto the stack, asm will put that constant in the constant pool for you
            numCounting.add(new InsnNode(Opcodes.IADD));
            numCounting.add(new FieldInsnNode(Opcodes.PUTSTATIC, classNode_c.name, "count", "I"));    
            mn.instructions.insert(node, numCounting);

(My usual approach with asm is to write the method i want to generate with asm in pure java, compile it and look at the resulting bytecode with javap. Thats usually a good indication what opcodes to use.)

  • Related