maven依赖:
<dependency>
<groupId>com.github.dozermapper</groupId>
<artifactId>dozer-core</artifactId>
<version>6.5.2</version>
</dependency>
工具类:
public class BeanMapper {
private static final Mapper MAPPER = DozerBeanMapperBuilder.buildDefault();
private BeanMapper() {
}
public static <S, D> D map(S source, Class<D> destinationClass) {
return null == source ? null : MAPPER.map(source, destinationClass);
}
public static <S, D> List<D> mapList(Iterable<S> sourceList, Class<D> destinationClass) {
if (null == sourceList) {
return null;
} else {
List<D> destinationList = new ArrayList<>();
for (S source : sourceList) {
if (source != null) {
destinationList.add(MAPPER.map(source, destinationClass));
}
}
return destinationList;
}
}
public static <S, D> D[] mapArray(final S[] sourceArray, final Class<D> destinationClass) {
if (null == sourceArray) {
return null;
} else {
@SuppressWarnings("unchecked")
D[] destinationArray = (D[]) Array.newInstance(destinationClass, sourceArray.length);
int i = 0;
for (S source : sourceArray) {
if (source != null) {
destinationArray[i] = MAPPER.map(source, destinationClass);
++i;
}
}
return destinationArray;
}
}
public static void copy(Object source, Object destinationObject) {
MAPPER.map(source, destinationObject);
}
}
转换list示例:
List<A> listA = new ArrayList<>();
List<B> listB = new ArrayList<>();
list = BeanMapper.mapList(listA, B.class);
list = entities.stream().map(entity -> {
ChannelRuleDTO deliverRuleVO = new ChannelRuleDTO();
BeanUtils.copyProperties(entity, deliverRuleVO);
return deliverRuleVO;
}).collect(Collectors.toList());
|