首页 > 解决方案 > 如何在 ByteBuddy 转换期间增加方法?

问题描述

标签: javabytecodebyte-buddybytecode-manipulation

解决方案


Can you share a reconstruction of your example? In a simple example, I observe the expected behavior:

public class Bar {
  public static void main(String[] args) throws Exception {
    Class<?> type = new ByteBuddy().subclass(Object.class)
      .visit(Advice.to(Bar.class).on(named("m")))
      .defineMethod("m", void.class, Visibility.PUBLIC)
      .intercept(MethodDelegation.to(Bar.class))
      .make()
      .load(Bar.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
      .getLoaded();

    type.getMethod("m").invoke(type.getConstructor().newInstance());
  }

  @BindingPriority(2)
  public static void delegation() {
    System.out.println("Delegation!");
  }

  @Advice.OnMethodEnter
  public static void enter() {
    System.out.println("Advice!");
  }
}

This example prints both Advice! and Delegation!.


推荐阅读