【问题标题】:Can Byte Buddy create fields and method annotations at runtime?Byte Buddy 可以在运行时创建字段和方法注解吗?
【发布时间】:2016-01-18 14:38:27
【问题描述】:

我想实现这个第 3 方注释以将我的类的字段/属性映射到我的数据库表列。我可以在编译时轻松实现注释(如下面的示例代码所示),但我找不到在运行时执行此操作的方法。 (我在运行时使用反射加载库。)

我的问题是如何在运行时加载库时实现相同的映射注释? Byte Buddy 可以为 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;
        }
    }

【问题讨论】:

    标签: java android annotations runtime byte-buddy


    【解决方案1】:

    可以,详情请咨询the Annotations section of the documentation

    您可以通过以下方式使用AnnotationDescription.Builder 构建注释:

    AnnotationDescription.Builder.ofType(MapToProperty.class)
                                 .define("property", "<value>")
                                 .build();
    

    生成的AnnotationDescription 可以作为参数提供给动态类型构建器:

    new ByteBuddy()
      .subclass(Object.class)
      .defineField("foo", Void.class)
      .annotateField(annotationDescription)
      .make();
    

    同样,它也适用于方法。

    【讨论】:

    • 类人 { 字符串名称;年龄; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; }
    • 谢谢。我可以应用类似的方法在运行时在现有类上添加注释吗?我正在使用 Byte-Buddy、Byte-Buddy-Android 和 dx。
    • 理论上可以,但是Android没有实现Java的instrumentation API。因此,只有将类文件嵌入到应用程序中并且修改后的类由新的类加载器加载时才有可能。
    • @RafaelWinterhalter 您能否解释一下如何在不更改方法实现的情况下使其适用于方法?真的很感激,找不到一个很好的例子:(
    猜你喜欢
    • 2017-04-03
    • 2022-11-11
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多