显示生成的bytebuddy字节码

时间:2015-06-16 05:25:09

标签: java bytecode byte-buddy

我正在使用ByteBuddy在运行时使用动态生成的字节代码创建一个类。生成的类执行它要执行的操作,但我想手动检查生成的字节代码,以确保它是正确的。

例如

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

其中MyImplementation将多个StackManipulation命令链接在一起以创建动态生成的代码。

我可以将生成的类写入文件(因此我可以使用IDE手动检查),或者打印出生成的类的字节码吗?

2 个答案:

答案 0 :(得分:11)

您可以将该类保存为.class文件:

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

此代码会创建c:/temp/Foo.class

答案 1 :(得分:2)

下面找一个将生成的类的字节存储在字节数组中的示例。以及如何将类保存到文件系统并可以从此数组中实例化。

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();
    }
}