Byte Buddy可以在运行时创建字段和方法注释吗? [英] Can Byte Buddy create fields and method annotations at runtime?
问题描述
我想实现此第三方注释,以将班级的字段/属性映射到我的数据库表列.我可以在编译时轻松实现注释(如下面的示例代码所示),但是我找不到在运行时执行此操作的方法. (我正在使用反射在运行时加载库.)
I would like to implement this 3rd-party annotation to map my class's fields/properties to my database table columns. I can easily implement the annotations at compile time (as shown in the example code below) but I can't find a way to do this at runtime. (I am loading the library at runtime using reflection.)
我的问题是在运行时加载库时如何实现相同的映射注释? Byte Buddy可以为Android处理吗?
My question is how can I implement the same mapping annotation when loading a library at run time? Can Byte Buddy handle this for Android?
//3rd party annotation code
package weborb.service;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface MapToProperty {
String property();
}
///////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//Here is the implementation using non-reflection
import weborb.service;
Class Person
{
@MapToProperty(property="Person_Name")
String name;
@MapToProperty(property="Person_Age")
int age;
@MaptoProperty(property="Person_Name")
public String getName()
{
return this.name;
}
@MaptoProperty(property="Person_Name")
public void setName(String name)
{
this.name = name;
}
@MaptoProperty(property="Person_Age")
public int getAge()
{
return this.age;
}
@MaptoProperty(property="Person_Age")
public void setAge(int age)
{
this.age = age;
}
}
推荐答案
是的,请参考 注释文档中的部分.
Yes, please refer to the Annotations section of the documentation for details.
您可以使用AnnotationDescription.Builder
通过以下方式构建注释:
You can build an annotation using an AnnotationDescription.Builder
by:
AnnotationDescription.Builder.ofType(MapToProperty.class)
.define("property", "<value>")
.build();
生成的AnnotationDescription
可以作为参数提供给动态类型生成器:
The resulting AnnotationDescription
can be supplied to a dynamic type builder as an argument:
new ByteBuddy()
.subclass(Object.class)
.defineField("foo", Void.class)
.annotateField(annotationDescription)
.make();
类似地,它适用于方法.
Similarly, it works for methods.
这篇关于Byte Buddy可以在运行时创建字段和方法注释吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!