Byte Buddy 和 OSGi Weaving Hook
Byte Buddy and OSGi Weaving Hook
我想将 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();
}
}
}
}
字节好友如何处理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())...
rebase
方法被重载并接受 ClassFileLocator
作为第二个参数。您可以通过提供显式映射直接提供 class 字节:
ClassFileLocator.Simple.of(wovenClass.getTypeDescription().getName(), wovenClass.getBytes())
我想将 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();
}
}
}
}
字节好友如何处理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())...
rebase
方法被重载并接受 ClassFileLocator
作为第二个参数。您可以通过提供显式映射直接提供 class 字节:
ClassFileLocator.Simple.of(wovenClass.getTypeDescription().getName(), wovenClass.getBytes())