字节好友和OSGi编织钩

时间:2019-01-21 23:15:04

标签: java osgi byte-buddy

我想将Byte Buddy与OSGi编织钩一起使用。

例如,可以将Javassist与OSGi编织钩一起使用,如下所示:

//... 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();
            }
        }

    }

}

如何使用Byte Buddy处理wovenClass?我看到我可以像这样取出字节码:

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

但是我看不到如何提供wovenClass字节码作为Byte Buddy的输入。我需要类似的东西:

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

1 个答案:

答案 0 :(得分:2)

rebase方法已重载,并接受ClassFileLocator作为第二个参数。您可以通过提供显式映射直接提供类字节:

ClassFileLocator.Simple.of(wovenClass.getTypeDescription().getName(), wovenClass.getBytes())