[英]Yet another copy of non-zero/non-null attributes from one instance to another thread, nested approach / Java
I'd like to find a clever way to deep copy all non-zero/non-null attributes from one instance of a class to another.我想找到一种巧妙的方法来将所有非零/非空属性从一个类的一个实例深复制到另一个实例。 If an attribute is a class, this class' attributes should be copied.
如果一个属性是一个类,这个类的属性应该被复制。 Tried BeanUtils (apache/spring) but was not able to copy nested attributes.
尝试 BeanUtils (apache/spring),但无法复制嵌套属性。
Let's assume:让我们假设:
private class ClassA {
String stringA;
int intA;
}
private class ClassB {
String stringB;
int intB;
ClassA objA;
}
private class ClassC {
String fieldC;
int intC;
ClassB objB;
}
ClassC outdated, updated;
magicMethod(outdated, updated);
Let's take stringB attribute into consideration, magicMethod(...) should behave like this:让我们考虑 stringB 属性,magicMethod(...) 应该像这样:
if(updated.objB != null && updated.objB.stringB != null) {
if(outdated.objB == null)
outdated.objB = new classB();
outdated.objB.stringB = updated.objB.stringB;
}
Same with primitive types, let's take int:与原始类型相同,让我们以 int 为例:
if(updated.objB != null && updated.objB.int != 0) {
if(outdated.objB == null)
outdated.objB = new classB();
outdated.objB.intB = updated.objB.intB;
}
Figured it out using orika mapper.使用orika映射器解决了这个问题。
public static class DataFilter extends NullFilter<Object, Object> {
public <S, D> boolean shouldMap(final Type<S> sourceType, final String sourceName, final S source,
final Type<D> destType, final String destName, final D dest, final MappingContext mappingContext) {
if (source instanceof String && ((String) source).isEmpty())
return false;
else if (source instanceof Integer && ((Integer) source).intValue() == 0)
return false;
return true;
}
}
Then然后
MapperFactory mapperFactory = new DefaultMapperFactory.Builder().mapNulls(false).build();
mapperFactory.registerFilter(new DataFilter());
mapperFactory.getMapperFacade().map(source, target);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.