[英]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. someField
的Pojo
和someSubField
的SubPojo
都标有特殊@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:
只是清理并获得释放的绿灯,但关键点是:
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 objectsFieldUtils.readField(field, node, true)
进行遍历 - 为了用您的 Annotation 注释所有字段,还有一个直接方法FieldUtils.getFieldsListWithAnnotation()
但我需要一种更灵活的方法来首先扫描所有节点,所以我可以深入研究子对象FieldUtils.writeField(field, node, getMyValueForField(field), true);
FieldUtils.writeField(field, node, getMyValueForField(field), true);
Caveats:注意事项:
ObjectGraphIterator
, but found it not suitable for my purpose.ObjectGraphIterator
,但发现它不适合我的目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.