Use of ByteBuddy's MemberSubstitution class

柔情痞子 提交于 2021-02-08 10:53:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!