2

How to create parametrized class in byte-buddy? For example:


    static public class SomeClass < T > {
      T value;
    }



    Class<?> dynamicType = new ByteBuddy()
                   .subclass(Object.class)
                   .defineField("value", ???, Modifier.PUBLIC)
                   .make()
                   .load(Main.class.getClassLoader())
                   .getLoaded();

  • 1
    Generics in java are intended for the compiler. There are no parameterized classes at runtime. Maybe this will help explain: [Type Erasure](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html) – Abra May 08 '20 at 07:23
  • Does this help? [Define field with generic type using ByteBuddy](https://stackoverflow.com/questions/45864313/define-field-with-generic-type-using-bytebuddy) – Abra May 08 '20 at 07:28
  • 2
    There are of course generic types at runtime. The JVM does not process it but it is available as meta data that can be read using the reflection API. – Rafael Winterhalter May 12 '20 at 10:47

1 Answers1

2

As simple as:

new ByteBuddy().subclass(Object.class)
  .typeVariable("T")
  .defineField("value", TypeDescription.Generic.Builder.typeVariable("T").build(), Modifier.PUBLIC);
Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192