我想使用 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/