ByteBuddy generic method return cast to concrete type

ekaqu :

I am trying to use byte buddy to work with protobuf data and having a hard time with the generic extensions APIs.

DynamicType.Builder<?> addSetter(final Class<? extends Message> container,
                                 final GeneratedExtension<?, ?> extension,
                                 final DynamicType.Builder<?> builder) throws NoSuchMethodException {
Method toBuilderMethod = container.getMethod("toBuilder");
Class<?> messageBuilderType = toBuilderMethod.getReturnType();

// generic return type is com.google.protobuf.GeneratedMessage.ExtendableBuilder
Method setterMethod = messageBuilderType.getMethod("setExtension", GeneratedExtension.class, Object.class);
Method buildMethod = messageBuilderType.getMethod("build");

MethodCall toBuilder = invoke(toBuilderMethod).onArgument(0);
MethodCall setit = invoke(setterMethod).onMethodCall(toBuilder).with(extension).withArgument(1);
MethodCall body = invoke(buildMethod).onMethodCall(setit) ;

return builder.method(named("set0")).intercept(body);

Here is the code from protobuf

public abstract static class ExtendableBuilder<
        MessageType extends ExtendableMessage,
        BuilderType extends ExtendableBuilder>
      extends Builder<BuilderType>
...
public final <Type> BuilderType setExtension(
        final GeneratedExtension<MessageType, List<Type>> extension,
        final int index, final Type value) {
...

Is there any way to change the return type of setit so I can get it to be the builder type messageBuilderType? I can't find a way to explicitly add a cast and can't find a API to override method return.

Thanks

Rafael Winterhalter :

From the type information being present, this is not possible. You can either create a generic representation of the method as a MethodDescription to make the static type compatible. As an easier solution, you can just configure add

withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC)

where Byte Buddy simply casts the generic type which would be the consequence of a generic assignment, too.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=145554&siteId=1