Reputation: 16238
I have a TypeDescription.Generic
built like this:
import static net.bytebuddy.description.type.TypeDescription.Generic.Builder.parameterizedType;
final TypeDescription.Generic supplierType =
parameterizedType(typePool.describe("java.util.function.Supplier").resolve(),
List.of(TypeDescription.Generic.Builder.of(mySuperclass.asGenericType()).asWildcardUpperBound()))
.build();
(mySuperclass
is a non-generic class, i.e. a simple TypeDescription
.)
I believe that supplierType
accurately represents java.util.function.Supplier<? extends MySuperclass>
.
Next, in a DynamicType.Builder
(using a subclassing strategy), I define a private
field using this supplierType
:
builder = builder.defineField("$supplier", supplierType, PRIVATE, SYNTHETIC, FieldManifestation.FINAL);
I believe that this field definition accurately represents private final Supplier<? extends MySuperclass> $supplier;
.
Next, I define a method returning the result of invoking get()
on that Supplier
:
builder = builder
.defineMethod("$get", mySuperclass, PUBLIC, SYNTHETIC, MethodManifestation.FINAL)
.intercept(MethodCall.invoke(named("get"))
.onField("$supplier")
.withAssigner(Assigner.DEFAULT,
Assigner.Typing.DYNAMIC)); // <-- my question
I believe that this method definition accurately represents public final MySuperclass $get() { return $supplier.get(); }
, but I have a question about its return type and casting and dynamic assignment.
Without the withAssigner
configuration, at runtime the $get()
method in my generated class fails, saying basically that the Supplier
in question cannot return a T
as a mySuperclass
.
I thought that because of the upper bound of the Supplier
's wildcard type argument, which is mySuperclass
, I wouldn't need this dynamic assignment. What have I misunderstood?
Upvotes: 1
Views: 20
Reputation: 44032
Byte Buddy works on byte code. You do not have to add the cast in Java, because the compiler adds it for you, but it will still be present in the byte code. get
will return an object type, and it is then casted to T
by the compiler.
Upvotes: 1