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

io.magentys.cinnamon.converter.MapToObjectReflectionConverter Maven / Gradle / Ivy

There is a newer version: 0.2.0
Show newest version
package io.magentys.cinnamon.converter;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Map.Entry;

public class MapToObjectReflectionConverter implements Converter, T> {

    private final Class type;

    public MapToObjectReflectionConverter(final Class type) {
        this.type = type;
    }

    @Override
    public T convert(final Map source) {

        try {
            final T mappedType = type.newInstance();

            for (final Entry entry : source.entrySet()) {

                try {
                    final Field fieldName = type.getDeclaredField(entry.getKey());

                    fieldName.setAccessible(true);
                    fieldName.set(mappedType, entry.getValue());
                } catch (final NoSuchFieldException e) {
                    // ignore
                } catch (final SecurityException e) {
                    throw new AssertionError("Failed to populate type: " + type, e);
                }
            }

            return mappedType;
        } catch (final InstantiationException | IllegalAccessException e) {
            throw new IllegalArgumentException(type.getClass().getName() + " should have a public no-arguments constructor.", e);
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy