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 ... else mv.visitVarInsn(ALOAD, 1);
Advertisement
Answer
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.