How can I generate method with byte buddy?

久未见 提交于 2019-12-25 02:57:15

问题


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).



来源:https://stackoverflow.com/questions/54300323/how-can-i-generate-method-with-byte-buddy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!