    001package javax.visrec.util;
    002
    003import java.lang.reflect.InvocationTargetException;
    004import java.lang.reflect.Method;
    005import java.util.Map;
    006
    007/**
    008 * Generic builder interface, that all builders for machine learning algorithms implement.
    009 *
    010 * @author Zoran Sevarac
    011 * @author Kevin Berendsen
    012 * @param <T> type of the object to be returned by the builder.
    013 * @since 1.0
    014 */
    015public interface Builder<T> {
    016
    017    /**
    018     * Builds and returns an object using properties set using available builder methods.
    019     *
    020     * @return object specified by the builder to build
    021     */
    022    T build();
    023
    024    /**
    025     * Builds an object using properties from the specified input argument
    026     *
    027     * @param configuration properties for the builder, a map of key, value pairs.
    028     * @return object specified by the builder to build
    029     */
    030    default T build(Map<String, Object> configuration) {
    031        Method[] methods = this.getClass().getDeclaredMethods();
    032        for (Method method : methods) {
    033            if (!method.getName().equals("build") && method.getParameterCount() == 1
    034                    && configuration.containsKey(method.getName())) {
    035                try {
    036                    method.invoke(this, configuration.get(method.getName()));
    037                } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
    038                    throw new InvalidBuilderConfigurationException("Couldn't invoke '" + method.getName() + "'", e);
    039                }
    040            }
    041        }
    042        return build();
    043    }
    044
    045}