Can Byte Buddy create fields and method annotations at runtime?

房东的猫 提交于 2019-12-23 03:51:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!