org.simpleflatmapper.map.asm.MapperAsmFactory Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sfm-map Show documentation
Show all versions of sfm-map Show documentation
Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.
package org.simpleflatmapper.map.asm;
import org.simpleflatmapper.map.FieldKey;
import org.simpleflatmapper.map.FieldMapper;
import org.simpleflatmapper.map.Mapper;
import org.simpleflatmapper.map.MappingContext;
import org.simpleflatmapper.reflect.BiInstantiator;
import org.simpleflatmapper.reflect.Instantiator;
import org.simpleflatmapper.reflect.asm.AsmFactory;
import java.lang.reflect.Constructor;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class MapperAsmFactory {
private final AsmFactory asmFactory;
public MapperAsmFactory(AsmFactory asmFactory) {
this.asmFactory = asmFactory;
}
private final ConcurrentMap>> fieldMapperCache = new ConcurrentHashMap>>();
private String generateClassNameForFieldMapper(final FieldMapper[] mappers, final FieldMapper[] constructorMappers, final Class super S> source, final Class target) {
StringBuilder sb = new StringBuilder();
sb.append("org.simpleflatmapper.map.generated.");
sb.append(asmFactory.getPackageName(target));
sb.append(".AsmMapperFrom").append(asmFactory.replaceArray(source.getSimpleName()));
sb.append("To").append(asmFactory.replaceArray(target.getSimpleName()));
if (constructorMappers.length > 0) {
sb.append("ConstInj").append(constructorMappers.length);
}
if (mappers.length > 0) {
sb.append("Inj").append(mappers.length);
}
sb.append("_I").append(Long.toHexString(asmFactory.getNextClassNumber()));
return sb.toString();
}
@SuppressWarnings("unchecked")
public Mapper createMapper(final FieldKey>[] keys,
final FieldMapper[] mappers,
final FieldMapper[] constructorMappers,
final BiInstantiator, T> instantiator,
final Class super S> source,
final Class target) throws Exception {
MapperKey key = new MapperKey(keys, mappers, constructorMappers, instantiator, target, source);
Class> type = (Class>) fieldMapperCache.get(key);
if (type == null) {
final String className = generateClassNameForFieldMapper(mappers, constructorMappers, source, target);
final byte[] bytes = MapperAsmBuilder.dump(className, mappers, constructorMappers, source, target);
type = (Class>) asmFactory.createClass(className, bytes, target.getClass().getClassLoader());
fieldMapperCache.put(key, type);
}
final Constructor> constructor = type.getDeclaredConstructors()[0];
return (Mapper) constructor.newInstance(mappers, constructorMappers, instantiator);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy