[英]Display generated bytebuddy bytecode
我正在使用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手動檢查),或者打印出生成的類的字節碼嗎?
您可以將類保存為.class文件:
new ByteBuddy()
.subclass(Object.class)
.name("Foo")
.make()
.saveIn(new File("c:/temp"));
此代碼創建c:/temp/Foo.class
。
下面是一個示例,用於將生成的類的字節存儲在字節數組中。 以及如何將類保存到文件系統並可以從此數組實例化。
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.