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

标签 java annotations byte-buddy

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

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

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

最佳答案

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

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() 方法之后你得到卸载的类,只需加载类并使用它。

下面是接口(interface)类的反射api的一些打印

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

关于java - 在字节好友中生成参数注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49091406/

相关文章:

java - 更改省电模式的状态(开/关)

java - 如何使用 byte-buddy 在运行时覆盖对象的值

java - 使用 ByteBuddy 的没有空构造函数的类的代理

java - 具有操作传递的装饰器模式?

java - 空抽象类是一种不好的做法吗?为什么?

java - 如何使用itext中签名的pdf上的注释添加用户定义的外观图标?或者这可能吗?

java - 如何读取注释文件?

jvm - 使用 ByteBuddy 代理重新定义 Spigot 类时出现 VerifyError

java - 应用程序错误 : ClassNotFoundException - TTT. jar - Java Applet

java - 继承方法的切入点(在与类设计无关的上下文中)