Skip to content

ASM: how to easily get proper Opcode based on type

I am using ASM to generate Java bytecode. I have a need to create a dynamic proxy which can override basically any kind of method with additional post-processing. I am able to do it all, but there is one thing I can’t see how to do in a nice way.

The type of the first parameter to the method I am overriding can be anything, so I can’t use ALOAD in the ASM code, but I might need to use ILOAD, LLOAD, FLOAD etc. My question: based on parameter type I want to load, is there a way to easily know which LOAD instruction opcode is valid, so I don’t have to do something like:

if (parameterType == int.class)
    mv.visitVarInsn(ILOAD, 1);
else if 
    mv.visitVarInsn(ALOAD, 1);



Assuming parameterType is of type Class OR of type String containing a type descriptor (like "I" or "Ljava/lang/String;"), then:

import org.objectweb.asm.Type;


Type parameterAsmType = Type.getType(parameterType);
int opcode = parameterAsmType.getOpcode(Opcodes.ILOAD);
mv.visitVarInsn(opcode, 1);

Similarly for other opcodes. See the Type.getOpcode() javadoc for details.

1 People found this is helpful