Java MethodAdapter-class And Method Code Example

In ASM, a MethodAdapter is a class that can be used to modify the bytecode of a Java method. It is typically used in conjunction with a ClassReader to read and modify the bytecode of an existing class.

Here is an example of how you might use a MethodAdapter to modify the bytecode of a method:

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

public class Example {
    public static void main(String[] args) throws Exception {
        // Read the class file as a byte array
        byte[] bytes = readClassFile();

        // Use the ClassReader to parse the bytecode
        ClassReader cr = new ClassReader(bytes);

        // Create a ClassVisitor that will be used to visit the methods of the class
        ClassVisitor cv = new ClassVisitor(Opcodes.ASM8) {
            public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
                // Return a MethodAdapter that will be used to modify the bytecode of the method
                return new MethodAdapter(Opcodes.ASM8, super.visitMethod(access, name, desc, signature, exceptions)) {
                    // Override the visitInsn method to insert new bytecode instructions before the RETURN instruction
                    public void visitInsn(int opcode) {
                        if (opcode == Opcodes.RETURN) {
                            // Insert a new instruction to print "Hello, World!"
                            visitLdcInsn("Hello, World!");
                            visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);

        // Have the ClassReader accept the ClassVisitor, which will cause it to call the appropriate methods
        cr.accept(cv, ClassReader.SKIP_DEBUG);

In this example, the MethodAdapter is used to modify the bytecode of a method by overriding the visitInsn method. When the visitInsn method is called with an opcode of Opcodes.RETURN, it inserts two new instructions to print "Hello, World!" before the RETURN instruction. This will cause the modified method to print this message before returning.