简体   繁体   English

对 POJO (Java) 的所有带注释的字段应用过滤器

[英]Apply filter on all annotated fields of a POJO (Java)

Imagine that there are such kind of POJO classes, that just keep data:想象一下,有这样一种 POJO 类,它们只保留数据:

public class Pojo() {

  @AnnotatedProp
  String someField;

  SubPojo someSubPojo;

  String someOtherFieldA;

  String someOtherFieldB;
}

public class SubPojo() {

  @AnnotatedProp
  String someSubField;

  Integer someOtherFieldC;
}

someField of Pojo and someSubField of SubPojo are marked special with the @AnnotatedProp property. someFieldPojosomeSubFieldSubPojo都标有特殊@AnnotatedProp财产。

I'd like to modify an object of type Pojo .我想修改Pojo类型的对象。 All String fields with @AnnotatedProp annotation should be modified.应修改所有带有@AnnotatedProp注释的 String 字段。 A "filter" should modify the values of these fields, eg replace some characters inside. “过滤器”应该修改这些字段的值,例如替换里面的一些字符。

I tried with FieldUtils / simple reflection, but I ended up in stack overflows (the exception AND this forum).我尝试使用 FieldUtils / 简单反射,但最终导致堆栈溢出(异常和此论坛)。

What would be the best way to filter these fields?过滤这些字段的最佳方法是什么?

Thanks for help.感谢帮助。

I've written a recursive POJO filter/transformer doing just that, because I needed it for a project.我已经编写了一个递归 POJO 过滤器/转换器来做到这一点,因为我需要它用于一个项目。 Just cleaning up and getting green light for release, but the key points are:只是清理并获得释放的绿灯,但关键点是:

  • use FieldUtils.readField(field, node, true) for traversal - for getting all fields annotated with your Annotation, there is also a direct method FieldUtils.getFieldsListWithAnnotation() but I needed a more flexible way to scan all nodes first, so I can drill down on sub objects使用FieldUtils.readField(field, node, true)进行遍历 - 为了用您的 Annotation 注释所有字段,还有一个直接方法FieldUtils.getFieldsListWithAnnotation()但我需要一种更灵活的方法来首先扫描所有节点,所以我可以深入研究子对象
  • you need to check against your own base package name to identify your custom POJO classes and only traverse those sub objects.您需要检查您自己的基本包名称以识别您的自定义 POJO 类并且仅遍历这些子对象。
  • once you have your annotated field, you can simply use FieldUtils.writeField(field, node, getMyValueForField(field), true);一旦你有你的注释字段,你可以简单地使用FieldUtils.writeField(field, node, getMyValueForField(field), true);

Caveats:注意事项:

  • to avoid a StackOverflow for back-references (child->ancestor), I keep a HashMap and store the FQCN of the nodes I traverse into为了避免反向引用的 StackOverflow (child->ancestor),我保留了一个 HashMap 并存储了我遍历到的节点的 FQCN
  • before rolling my own, I checked Apache commons ObjectGraphIterator , but found it not suitable for my purpose.在自己动手之前,我检查了 Apache commons ObjectGraphIterator ,但发现它不适合我的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM