Skip to content

Instantly share code, notes, and snippets.

@wypk
Created April 30, 2018 14:57
Show Gist options
  • Save wypk/74d58acbb767293d603bbce184807b09 to your computer and use it in GitHub Desktop.
Save wypk/74d58acbb767293d603bbce184807b09 to your computer and use it in GitHub Desktop.
public class ModelMapperService {
/** The Constant LOG. */
private static final Logger LOG = LogManager.getLogger(ModelMapperService.class);
/** The model mapper. */
private ModelMapper modelMapper = new ModelMapper();
/**
* Instantiates a new model mapper service.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public ModelMapperService() {
this.modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
Condition notNull = new Condition() {
@Override
public boolean applies(MappingContext context) {
return context.getSource() != null;
}
};
this.modelMapper.getConfiguration()
.setPropertyCondition(notNull)
.setFieldMatchingEnabled(true)
.setFieldAccessLevel(AccessLevel.PRIVATE)
.setMethodAccessLevel(AccessLevel.PRIVATE);
Reflections reflections = new Reflections("com.ktzcompany");
// SubTypesScanner
Set<Class<? extends PropertyMap>> mappers = reflections.getSubTypesOf(PropertyMap.class);
Set<Class<? extends AbstractConverter>> converters = reflections.getSubTypesOf(AbstractConverter.class);
for (Class clazz : mappers) {
LOG.info("mapper : {}", clazz.getName());
try {
this.modelMapper.addMappings((PropertyMap) clazz.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
LOG.error(e);
}
}
for (Class clazz : converters) {
LOG.info("converter : {}", clazz.getName());
try {
this.modelMapper.addConverter((AbstractConverter) clazz.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
LOG.error(e);
}
}
}
/**
* Map.
*
* @param source
* the source
* @param destination
* the destination
*/
public void map(Object source, Object destination) {
this.modelMapper.map(source, destination);
}
/**
* Map.
*
* @param <S>
* the generic type
* @param <D>
* the generic type
* @param source
* the source
* @param destinationType
* the destination type
* @return the d
*/
public <S, D> D map(S source, Class<D> destinationType) {
return this.modelMapper.map(source, destinationType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment