【问题标题】:Can I inject a annotation into a pojo我可以在 pojo 中注入注释吗
【发布时间】:2016-10-17 03:02:12
【问题描述】:

假设我有一个看起来像这样的 POJO。

public class SomeDataClass {

    @SomeProperty1
    String myField1;

    @SomeProperty1
    String myField2;

    ...

    getters()... 
    setters()... // you know the drill

}

我希望能够综合地向实例化对象注入注释。新的 POJO,如果我使用反射来检查它,实际上看起来像这样:

public class SomeDataClass {

    @SomeProperty1
    String myField1;

    @SomeProperty1
--> @SomeProperty2 <--- the logic flow would change depending on whether this annotation is present
    String myField2;

    ...

    getters()... 
    setters()... // you know the drill

}

这可能吗?我怎么能完成这样的事情?

【问题讨论】:

  • 通过反射,您不检查实例,而是检查类(它们本身就是实例,但您知道我的意思)。
  • 注解是不变类结构的一部分。它们与实例化对象无关,因此不能注入到实例化对象中。 …而且它们是不可变的。

标签: java reflection annotations introspection


【解决方案1】:

Annotations 只是语法元数据提供者...

因此您应该通过反射获得给定类中声明的字段的名称,并使用所需的标准来区分其中哪个字段需要@SomeProperty2提供的信息,之后在运行时添加来自 @SomeProperty2 的信息只是 setter 或 getter 的正常使用...

【讨论】:

  • 问题是我有一个包含 2000 个字段定义的类。这是一个在 cobol 程序中表示数据字段的类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多