raphw / byte-buddy

Runtime code generation for the Java virtual machine.
https://bytebuddy.net
Apache License 2.0
6.23k stars 804 forks source link

Can I replace the new byte[] in the onTransformation method? #1584

Closed 17396900506 closed 6 days ago

17396900506 commented 8 months ago

I want to use jacoco's instrument() in the onTransformation() method to replace the new byte[] file. How can I let byte buddy load this replaced byte[] file?

@Override public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) { System.out.println("onTransformation=" + typeDescription.getName() + ",classLoader=" + classLoader); byte[] bytes = dynamicType.getBytes(); try { byte[] instrument = new Instrumenter(new LoggerRuntime()).instrument(bytes, typeDescription.getName()); } catch (IOException e) { throw new RuntimeException(e); } dynamicType.inject(); }

raphw commented 8 months ago

Why would you need ByteBuddy for this? Simply register a ClassFileTransformer and return the byte array you want to replace.