Search code examples
javabyte-buddy

Byte Buddy - how can make a field self type?


It is necessary to describe the structure of this class

class A{
    private List<A> listA;   
}

tried the solution: Byte-buddy: generate classes with cyclic types

but it will lead to an error

java.lang.ExceptionInInitializerError Caused by: java.lang.IllegalStateException: Cannot resolve declared type of a latent type description:...


Solution

  • You can use TargetType as a reference for the currently generated type:

    new ByteBuddy()
      .subclass(Object.class)
      .name("A")
      .defineField("listA", 
          TypeDescription.Generic.Builder.parameterizedType(
              List.class, TargetType.class).build(),
          Visibility.PRIVATE)
      .make()