问题
I am using ByteBuddy to substitute a field reference by another one into methods of a class. In another question I was suggested to use the class net.bytebuddy.asm.MemberSubstitution. I have been looking for examples about how to use this in mi java agent but a could not find any.
I want to use the following code:
MemberSubstitution.relaxed()
.field(ElementMatchers.named("oneField"))
.onRead()
.replaceWith(otherField);
My agent is:
public class MyAgent {
public static void premain(String arg, Instrumentation inst)
throws Exception {
File temp = Files.createTempDirectory("tmp").toFile();
ClassInjector.UsingInstrumentation.of(temp,
ClassInjector.UsingInstrumentation.Target.BOOTSTRAP, inst)
.inject(Collections.singletonMap(
new TypeDescription.ForLoadedType(MyInterceptor.class),
ClassFileLocator.ForClassLoader.read(MyInterceptor.class).resolve()));
new AgentBuilder.Default()
.enableBootstrapInjection(inst, temp)
.type(isAnnotatedWith(CriptoObject.class))
.transform(new AgentBuilder.Transformer() {
@Override
public DynamicType.Builder<?> transform(
DynamicType.Builder<?> builder,
TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module) {
return builder.method(any())
.intercept(MethodDelegation.to(MyInterceptor.class)
.andThen(SuperMethodCall.INSTANCE));
}
}).installOn(inst);
}
}
The interceptor code is
public class MyInterceptor {
public static void intercept(@Origin Method m, @This Object o)
throws Exception {
System.out.println("Intercepted!" + o.getClass().getField("b").get(o));
}
}
I don't know where to place the MemberSubstitution code to transform a specific method.
Please, can someone help me with this?
Thank in advance
回答1:
Its a visitor that transforms existing code without adding anything where you register it via:
builder = builder.visit(MemberSubstitution.relaxed()
.field(ElementMatchers.named("oneField"))
.onRead()
.replaceWith(otherField)
.on(method(any()));
来源:https://stackoverflow.com/questions/51637694/use-of-bytebuddys-membersubstitution-class