bytebuddy official demo throw Exception "Class already loaded: class foo.Bar"

Viewed 73

Section "Working with unloaded classes" in Official document give a demo, I run it on my machine then throw an exception Class already loaded: class foo.Bar。

class MyApplication {
  public static void main(String[] args) {
    TypePool typePool = TypePool.Default.ofSystemLoader();
    new ByteBuddy()
      .redefine(typePool.describe("foo.Bar").resolve(), // do not use 'Bar.class'
                ClassFileLocator.ForClassLoader.ofSystemLoader())
      .defineField("qux", String.class) // we learn more about defining fields later
      .make()
      .load(ClassLoader.getSystemClassLoader());
    assertThat(Bar.class.getDeclaredField("qux"), notNullValue());
  }
}

bytebuddy version is 1.10.22

1 Answers

The problem is in the last line Bar.class.getDeclaredField("qux") which loads the Bar class upon validation of the code. I fixed this in the example. Rather use the return value of load which returns Bar.

Related