bytebuddy: make array of generic

Viewed 192

i want to make class:

class Clazz<T>{
 T[] value;
}


TypeDescription.Generic t1 = TypeDescription.Generic.Builder.typeVariable("T").asArray().build();

new ByteBuddy().subclass(Object.class)
            .typeVariable("T")
            .defineField("value", t1, Modifier.PUBLIC)
            .make()

but i get exception

Exception in thread "main" java.lang.IllegalStateException: A symbolic type variable does not imply an erasure: T
at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable$Symbolic.asErasure(TypeDescription.java:5802)

how i can make T[] field?

3 Answers

You stumbled upon a bug. Byte Buddy attempts to resolve TargetType references to identify the instrumented type's self type which is not done correctly for generic arrays. It will be fixed in the next version 1.10.11.

You can't. However, if you want, you can do this:

Object[] value = new Object[];

Then when accessing it:

T t = (T) value[index];

One option i found that works, is to use the field in class Clazz<T> as a prototype to defined the new field:

Unloaded<Object> cls = new ByteBuddy().subclass(Object.class).typeVariable("T")
            .defineField("value", Clazz.class.getDeclaredFields()[0].getGenericType(), Modifier.PUBLIC);
Related