Search code examples
byte-buddy

How to implement ClassFileTransformer#transform with byte buddy?


Is there a way to use byte buddy to implement ClassFileTransformer#transform? At the moment my implementation uses javassist but I want to replace it with byte buddy as it has a better generics support.

So far my implementation looks like this:

public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
  ProtectionDomain protectionDomain, byte[] classfileBuffer)
{
  if (className.startsWith("my.package."))
  {
    try {
      final CtClass ctClass = classPool.makeClass(new ByteArrayInputStream(classfileBuffer));
      /* class manipulation */
      return ctClass.toBytecode();

      // remove class from class pool if it hasn't been modified
      ctClass.detach();
    } catch(final Exception ex) {
      logger.error("failed to analyse/transform class {}", className, ex);
    }
  }

  return classfileBuffer;
}

Is something similar possible with byte buddy? Are there ways to feed byte buddy with the byte code provided in parameter classfileBuffer?

The ClassFileTransformer implementation is configured into the Spring Load Time Weaver. So I already have the "infrastructure" available. Therefore I would rather not install another byte buddy agent to solve this problem.


Solution

  • Yes, look into AgentBuilder.Default. It offers a DSL for implementing Java agents. You do not need to implement your own class file transformer using it, just specify the transformations you want to make.