All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.simpleflatmapper.map.mapper.GenericBuilder Maven / Gradle / Ivy

Go to download

Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.

There is a newer version: 9.0.2
Show newest version
package org.simpleflatmapper.map.mapper;

import org.simpleflatmapper.map.FieldMapper;
import org.simpleflatmapper.map.MappingContext;
import org.simpleflatmapper.reflect.BiInstantiator;
import org.simpleflatmapper.reflect.Setter;
import org.simpleflatmapper.util.ErrorHelper;
import org.simpleflatmapper.util.Function;

import java.lang.reflect.Method;

public final class GenericBuilder  {

    public static final Method BUILD;
    
    static {
        try {
            BUILD = GenericBuilder.class.getMethod("build");
        } catch (NoSuchMethodException e) {
            throw new Error("Unexpected error " + e, e);
        }
    }
    public final Object[] objects;
    public final BiInstantiator targetInstantiator;
    public final Setter>[] targetFieldSetters;
    public final FieldMapper>[] genericBuilderFieldMappers;

    public GenericBuilder(FieldMapper>[] genericBuilderFieldMappers, BiInstantiator targetInstantiator, Setter>[] targetFieldSetters) {
        this.objects = new Object[genericBuilderFieldMappers.length];
        this.genericBuilderFieldMappers = genericBuilderFieldMappers;
        this.targetInstantiator = targetInstantiator;
        this.targetFieldSetters = targetFieldSetters;
    }
    
    public T build() throws Exception {
        T t = targetInstantiator.newInstance(objects, this);
        for(Setter> setter : targetFieldSetters) {
            setter.set(t, this);
        }
        return t;
    }

    public void mapFrom(S source, MappingContext context) throws Exception {
        for(FieldMapper> fm : genericBuilderFieldMappers) {
            fm.mapTo(source, this, context);
        }
    }

    public static  Function, T> buildFunction() {
        return new GenericBuilderTransformFunction();
    }

    private static class GenericBuilderTransformFunction implements Function, T> {
        @Override
        public T apply(GenericBuilder o) {
            try {
                if (o == null) return null;
                return o.build();
            } catch (Exception e) {
                return ErrorHelper.rethrow(e);
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy