在字节好友中生成参数注解

Generate parameter annotations in Byte Buddy

我想用 ByteBuddy 生成这样的简单界面:

public interface MyInterface {
    void myMethod(@Deprecated String myDeprecatedParameter);
}

这只是一个例子,重点是方法的参数需要一些自定义注解。 有没有人有一个简单的例子来演示如何在 ByteBuddy 中实现这一点?

您可以创建一个带有注释参数的接口,如下所示。首先定义接口名称和修饰符,然后用它的名称、return 类型和修饰符定义方法,最后定义参数和注释(如果有的话)。

Class<?> myInterface = new ByteBuddy()
        .makeInterface()
        .name("MyInterface")
        .modifiers(Visibility.PUBLIC, TypeManifestation.ABSTRACT)
        .defineMethod("myMethod", void.class, Visibility.PUBLIC)
        .withParameter(String.class, "myDeprecatedParameter")
        .annotateParameter(AnnotationDescription.Builder.ofType(Deprecated.class)
                .build())
        .withoutCode()
        .make()
        .load(this.getClass().getClassLoader())
        .getLoaded();

如果需要多个注解,可以多次调用annotateParameter(...)

make() 方法后你得到卸载的 class,只需加载 class 并使用它。

这里有一些带有反射 api 界面 class 的印刷品。

System.out.println(Modifier.toString(myInterface.getModifiers())); // public abstract interface
System.out.println(myInterface.getSimpleName()); // MyInterface
System.out.println(Arrays.toString(myInterface.getDeclaredMethods())); // [public abstract void MyInterface.myMethod(java.lang.String)]

Method method = myInterface.getDeclaredMethod("myMethod", String.class);
System.out.println(method.getName()); // myMethod
System.out.println(Arrays.toString(method.getParameters())); // [java.lang.String myDeprecatedParameter]

Parameter parameter = method.getParameters()[0];
System.out.println(parameter); // java.lang.String myDeprecatedParameter
System.out.println(parameter.getName()); // myDeprecatedParameter
System.out.println(Arrays.toString(parameter.getAnnotations())); // [@java.lang.Deprecated()]

Annotation annotation = parameter.getAnnotations()[0];
System.out.println(annotation); // @java.lang.Deprecated()