Different sources offer different ways to implement ClassFileTransformer
with Javassist:
blog.newrelic.com/2014/09/29/diving-bytecode-manipulation-creating-audit-log-asm-javassist/
public byte[] transform(...) {
ClassPool pool = ClassPool.getDefault(); // Edited to simplify
pool.insertClassPath(new ByteArrayClassPath(className, classfileBuffer));
CtClass cclass = pool.get(className.replaceAll("/", "."));
...
return cclass.toBytecode();
}
blog.javabenchmark.org/2013/05/java-instrumentation-tutorial.html
public byte[] transform(...) {
ClassPool cp = ClassPool.getDefault();
CtClass cc = cp.get("org.javabenchmark.instrumentation.Sleeping");
...
return cc.to:byteCode(); // edited to simplify
}
http://javapapers.com/core-java/java-instrumentation/
public byte[] transform(...) {
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.makeClass(new ByteArrayInputStream(classfileBuffer));
...
return ctClass.to:byteCode(); // edited to simplify
}
Which is most correct way and why? Is there other solutions which are better than those three?
https://stackoverflow.com/a/26725215/776884 mentions settings correct classloader. Is it required when using instrumentation API? Should ClassPool classPool = new ClassPool()
with CtClass.makeClass()
be used with instumentation API?