Replace static block with ByteBuddy (not append code)
Given: existing class (bytecode)
Required: create a new class based on the existing class, replacing the static block initializer (not appending code)
So far, the following code appends commands to the static block
Class> templateClass;
String newFQCN;
DynamicType.Unloaded> unloaded = new ByteBuddy()
.redefine(templateClass)
.name(newFQCN)
.invokable(ElementMatchers.isTypeInitializer())
.intercept(new Implementation.Simple(
(mv, ctx, method) -> {
StackManipulation body =
generateClinit(method.getDeclaringType().asErasure());
// returns "StackManipulation", new code for the static block
StackManipulation.Size size = body.apply(mv, ctx);
mv.visitInsn(Opcodes.RETURN);
return new ByteCodeAppender.Size(
size.getMaximalSize(),
method.getStackSize()
);
}
))
.make();
Please recommend code edits that ensure replacing the static block, not appending code to it.