How can I generate method with byte buddy?

2019-08-28 12:54发布

问题:

This is a followup question of How can I get Annotation class from TypeDescription

I'm trying to generate methods using Plugin.

With given class such as.

class {

    @Func
    T some;
}

I located the field with specific annotation.

And I'm asking for help to create a method look like this.

public <R> R applySome(Function<T, R> function) {
    return function.apply(some);
}

How can I make the method in

@Override
public DynamicType.Builder<?> apply(final DynamicType.Builder<?> builder, final TypeDescription typeDescription,
                                    final ClassFileLocator classFileLocator) {
    System.out.printf("apply(%1$s, %2$s, %3$s)\n", builder, typeDescription, classFileLocator);
    final List<FieldDescription.InDefinedShape> fields = fields(typeDescription);
    fields.forEach(field -> {
        System.out.printf("\tfield: %1$s\n", field);
        System.out.printf("\tfield.name: %1$s\n", field.getName());
        System.out.printf("\tfield.type: %1$s\n", field.getType());
        System.out.printf("\tfield.declaringType: %1$s\n", field.getDeclaringType());
        // define the method.
    });
    return null;
}

回答1:

The DynamicType.Builder that you receive as an argument has a defineMethod method that allows for that. As an implementation, you can use MethodCall.invoke(Function.class.getMethod("apply")).onArgument(0).