Display generated bytebuddy bytecode

2.7k views Asked by At

I am using ByteBuddy to create a class at runtime with dynamically generated byte code. The generated class does what it is intended to do, but I want to manually inspect the generated byte code, to ensure it is correct.

For example

Class<?> dynamicType = new ByteBuddy()
        .subclass(MyAbstractClass.class)
        .method(named("mymethod"))
        .intercept(new MyImplementation(args))
        .make()
        .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
        .getLoaded();

where MyImplementation chains multiple StackManipulation commands together to create the dynamically generated code.

Can I write the generated class out to a file, (so I can manually inspect with a IDE), or otherwise print out the bytecode for the generated class?

2

There are 2 answers

0
AudioBubble On BEST ANSWER

You can save the class as .class file:

new ByteBuddy()
    .subclass(Object.class)
    .name("Foo")
    .make()
    .saveIn(new File("c:/temp"));

This code creates c:/temp/Foo.class.

2
SubOptimal On

Find below an example to store the bytes of the generated class in a byte array. And how the class can be saved to the file system and can be instantiated from this array.

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.instrumentation.FixedValue;
import static net.bytebuddy.instrumentation.method.matcher.MethodMatchers.named;

public class GenerateClass extends ClassLoader {

    void doStuff() throws Exception {
        byte[] classBytes = new ByteBuddy()
                .subclass(Object.class)
                .name("MyClass")
                .method(named("toString"))
                .intercept(FixedValue.value("Hello World!"))
                .make()
                .getBytes();

        // store the MyClass.class file on the file system
        Files.write(Paths.get("MyClass.class"), classBytes, StandardOpenOption.CREATE);

        // create an instance of the class from the byte array
        Class<?> defineClass = defineClass("MyClass", classBytes, 0, classBytes.length);
        System.out.println(defineClass.newInstance());
    }

    public static void main(String[] args) throws Exception {
        new GenerateClass().doStuff();
    }
}