Search code examples
javaosgibyte-buddy

Byte Buddy and OSGi Weaving Hook


I would like to use Byte Buddy together with OSGi weaving hook.

For instance, it is possible to use Javassist together with OSGi weaving hook like this:

//... other imports
import org.osgi.framework.hooks.weaving.WeavingHook;
import org.osgi.framework.hooks.weaving.WovenClass;

@Component (immediate = true)
public class MyWeavingHook implements WeavingHook {

    @Activate
    public void activate(ComponentContext ctx) {
        System.out.print("Activating demo weaving hook...");
    }

    @Override
    public void weave(WovenClass wovenClass) {
        System.out.println("Weaving hook called on " + wovenClass.getClassName());
        if (wovenClass.getClassName().equals("DecoratedTestServiceImpl")) {
            try (InputStream is = new ByteArrayInputStream(wovenClass.getBytes())) {
                ClassPool pool = ClassPool.getDefault();
                CtClass ctClass = pool.makeClass(is);
                ctClass.getDeclaredMethod("ping").setBody("return \"WAIVED\";");
                wovenClass.setBytes(ctClass.toBytecode());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}

How to process the wovenClass with Byte Buddy? I see that I can get the bytecode out like this:

byte[] classBytes = new ByteBuddy()
                .subclass(AClass.class)
                .name("MyClass")
                .method(named("theMethod"))
                .intercept(FixedValue.value("Hello World!"))
                .make()
                .getBytes();
wovenClass.setBytes(classBytes);

But I cannot see how to provide the wovenClass bytecode as an input to Byte Buddy. I would need something like:

new ByteBuddy().rebase(wovenClass.getBytes())...

Solution

  • The rebase method is overloaded and accepts a ClassFileLocator as a second argument. You can provide the class bytes directly by providing an explicit mapping:

    ClassFileLocator.Simple.of(wovenClass.getClassName(), wovenClass.getBytes())