I am using JMapper
to map from multiple sources to a destination class. Could you review it and let me know if the code looks OK to you? Please suggest any changes that I can make to improve it.
Interface to Map
sources to destination object:
public interface ObjectMapper<D> {
public D getDestination(Object... sources);
}
Class that implements this interface to perform the desired mapping using JMapper
:
import org.apache.commons.lang.WordUtils;
import com.googlecode.jmapper.JMapper;
public class JMapperImpl<S1, S2> implements ObjectMapper<DestinationClazz> {
private static ObjectMapper<DestinationClazz> INSTANCE;
private static final String CONVERSION_END = "Conversion.xml";
private Class<S1> source1;
private Class<S2> source2;
private final JMapper<DestinationClazz, S1> mapper1;
private final JMapper<DestinationClazz, S2> mapper2;
private JMapperImpl(Class<DestinationClazz> destination, Class<S1> source1, Class<S2> source2) {
final String mappingFile = getMappingFile(destination);
mapper1 = new JMapper<DestinationClazz, S1>(destination, source1, mappingFile);
mapper2 = new JMapper<DestinationClazz, S2>(destination, source2, mappingFile);
this.source1 = source1;
this.source2 = source2;
}
/**
* @param destination
* @return uncapitalizes the first letter of destination class name.
*/
private String getMappingFile(Class<DestinationClazz> destination) {
return WordUtils.uncapitalize(destination.getSimpleName())+CONVERSION_END;
}
public static <S1, S2> ObjectMapper<DestinationClazz> getJMapperInstance(Class<DestinationClazz> destination, Class<S1> source1, Class<S2> source2) {
if(INSTANCE == null) {
INSTANCE = new JMapperImpl<S1, S2>(destination, source1, source2);
}
return INSTANCE;
}
/**
* Returns new instance of destination object with its properties mapped from source objects
*/
@Override
public DestinationClazz getDestination(Object... sources) {
DestinationClazz destination;
try {
destination = DestinationClazz.class.newInstance();
for(Object source : sources) {
Class<? extends Object> sourceClass = source.getClass();
if(sourceClass == source1) {
destination = mapper1.getDestination(destination, (S1)source);
}
else if(sourceClass == source2) {
destination = mapper2.getDestination(destination, (S2)source);
}
}
} catch (InstantiationException e) {
throw new CustomException("Couldn't instantiate DestinationClazz class:"+e.getMessage());
} catch (IllegalAccessException e) {
throw new CustomException("Couldn't access DestinationClazz class:"+e.getMessage());
} catch (Exception e) {
throw new CustomException("Exception while mapping source objects to DestinationClazz object:"+e.getMessage());
}
return destination;
}
}