使用ByteBuddy重新定义方法时出错:"类重新定义失败:尝试添加方法"

时间:2016-11-23 21:48:15

标签: java instrumentation byte-buddy

我正在学习Byte Buddy,而我正在努力做到以下几点:

  • 从给定的类或接口创建子类
  • 然后替换子类中的方法

请注意,子类已被加载'在ClassLoader 之前重新定义其方法之一(sayHello)。它失败并显示以下错误消息:

java.lang.UnsupportedOperationException: class redefinition failed: attempted to add a method
at sun.instrument.InstrumentationImpl.redefineClasses0(Native Method)
at sun.instrument.InstrumentationImpl.redefineClasses(InstrumentationImpl.java:170)
at net.bytebuddy.dynamic.loading.ClassReloadingStrategy$Strategy$1.apply(ClassReloadingStrategy.java:293)
at net.bytebuddy.dynamic.loading.ClassReloadingStrategy.load(ClassReloadingStrategy.java:173)
...

下面是一组JUnit测试的代码。在重新定义其方法之前,第一个测试shouldReplaceMethodFromClass通过,因为Bar类未被子类化。当给定的Bar类或Foo接口被子类化时,另外两个测试失败。

我读到我应该将新方法委托给一个单独的类,这是我使用CustomInterceptor类所做的,我还在测试启动时安装了ByteBuddy代理并用于加载子类,但是即便如此,我仍然遗漏了一些东西,我无法看到:(

有人有想法吗?

public class ByteBuddyReplaceMethodInClassTest {

  private File classDir;

  private ByteBuddy bytebuddy;

  @BeforeClass
  public static void setupByteBuddyAgent() {
    ByteBuddyAgent.install();
  }

  @Before
  public void setupTest() throws IOException {
    this.classDir = Files.createTempDirectory("test").toFile();
    this.bytebuddy = new ByteBuddy().with(Implementation.Context.Disabled.Factory.INSTANCE);
  }

  @Test
  public void shouldReplaceMethodFromClass()
      throws InstantiationException, IllegalAccessException, Exception {
    // given
    final Class<? extends Bar> modifiedClass = replaceMethodInClass(Bar.class,
        ClassFileLocator.ForClassLoader.of(Bar.class.getClassLoader()));
    // when
    final String hello = modifiedClass.newInstance().sayHello();
    // then
    assertThat(hello).isEqualTo("Hello!");
  }

  @Test
  public void shouldReplaceMethodFromSubclass()
      throws InstantiationException, IllegalAccessException, Exception {
    // given
    final Class<? extends Bar> modifiedClass = replaceMethodInClass(createSubclass(Bar.class),
        new ClassFileLocator.ForFolder(this.classDir));
    // when
    final String hello = modifiedClass.newInstance().sayHello();
    // then
    assertThat(hello).isEqualTo("Hello!");
  }

  @Test
  public void shouldReplaceMethodFromInterface()
      throws InstantiationException, IllegalAccessException, Exception {
    // given
    final Class<? extends Foo> modifiedClass = replaceMethodInClass(createSubclass(Foo.class),
        new ClassFileLocator.ForFolder(this.classDir));
    // when
    final String hello = modifiedClass.newInstance().sayHello();
    // then
    assertThat(hello).isEqualTo("Hello!");
  }


  @SuppressWarnings("unchecked")
  private <T> Class<T> createSubclass(final Class<T> baseClass) {
    final Builder<T> subclass =
        this.bytebuddy.subclass(baseClass);
    final Loaded<T> loaded =
        subclass.make().load(ByteBuddyReplaceMethodInClassTest.class.getClassLoader(),
            ClassReloadingStrategy.fromInstalledAgent());
    try {
      loaded.saveIn(this.classDir);
      return (Class<T>) loaded.getLoaded();
    } catch (IOException e) {
      throw new RuntimeException("Failed to save subclass in a temporary directory", e);
    }
  }

  private <T> Class<? extends T> replaceMethodInClass(final Class<T> subclass,
      final ClassFileLocator classFileLocator) throws IOException {
    final Builder<? extends T> rebasedClassBuilder =
        this.bytebuddy.redefine(subclass, classFileLocator);
    return rebasedClassBuilder.method(ElementMatchers.named("sayHello"))
        .intercept(MethodDelegation.to(CustomInterceptor.class)).make()
        .load(ByteBuddyReplaceMethodInClassTest.class.getClassLoader(),
            ClassReloadingStrategy.fromInstalledAgent())
        .getLoaded();
  }

  static class CustomInterceptor {
    public static String intercept() {
      return "Hello!";
    }
  }


}

Foo接口和Bar类是:

public interface Foo {

    public String sayHello();

}

public class Bar {

    public String sayHello() throws Exception {
      return null;
    }

}

1 个答案:

答案 0 :(得分:1)

问题是您首先创建Bar的子类,然后加载它,但稍后重新定义它以添加方法sayHello。你的课程演变如下:

  1. 创建子类

    class Bar$ByteBuddy extends Bar {
      Bar$ByteBuddy() { ... }
    }
    
  2. 重新定义子类

    class Bar$ByteBuddy extends Bar {
      Bar$ByteBuddy() { ... }
      String sayHello() { ... }
    }
    
  3. HotSpot VM和大多数其他虚拟机不允许在类加载后添加方法。您可以通过在第一次定义子类之前将方法添加到子类来解决此问题,即设置:

    DynamicType.Loaded<T> loaded = bytebuddy.subclass(baseClass)
      .method(ElementMatchers.named("sayHello"))
      .intercept(SuperMethodCall.INSTANCE) // or StubMethod.INSTANCE
      .make()
    

    这样,当重新定义和Byte Buddy可以简单地替换其字节代码而不需要添加方法时,该方法已经存在。请注意,Byte Buddy尝试重新定义,因为一些虚拟机实际上支持它(很可能是动态代码进化VM,它希望在某些时候合并到HotSpot中,参见JEP 159)。