问题
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.)
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;
}
}
回答1:
Yes, please refer to the Annotations section of the documentation for details.
You can build an annotation using an AnnotationDescription.Builder
by:
AnnotationDescription.Builder.ofType(MapToProperty.class)
.define("property", "<value>")
.build();
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.
来源:https://stackoverflow.com/questions/34857309/can-byte-buddy-create-fields-and-method-annotations-at-runtime