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

ch.lambdaj.function.convert.ConstructorArgumentConverter Maven / Gradle / Ivy

There is a newer version: 2.3.3
Show newest version
// Modified or written by Ex Machina SAGL for inclusion with lambdaj.
// Copyright (c) 2009 Mario Fusco.
// Licensed under the Apache License, Version 2.0 (the "License")

package ch.lambdaj.function.convert;

import ch.lambdaj.util.*;

import java.lang.reflect.*;
import java.util.*;

/**
 * Creates an object of the given Class by invoking its constructor passing to it the values taken
 * from the object to be converted using the given arguments.
 * @author Mario Fusco
 */
public class ConstructorArgumentConverter implements Converter {

    private Constructor constructor;

    private final List> argumentConverters = new LinkedList>();

    public ConstructorArgumentConverter(Class clazz, Object... arguments) {
        for (Constructor c : clazz.getConstructors()) {
            if (isCompatible(c, arguments)) {
                this.constructor = (Constructor)c;
                break;
            }
        }

        if (constructor == null)
            throw new IntrospectionException("Unable to find a constructor of " + clazz.getName() + " compatible with the given arguments");

        if (arguments != null)
            for (Object argument : arguments) { argumentConverters.add(new ArgumentConverter(argument)); }
    }

    private boolean isCompatible(Constructor constructor, Object... arguments) {
        try {
            constructor.newInstance(arguments);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * {@inheritDoc}
     */
    public T convert(F from) {
        Object[] initArgs = new Object[argumentConverters.size()];
        int i = 0;
        for (ArgumentConverter argumentConverter : argumentConverters) {
            initArgs[i++] = argumentConverter.convert(from);
        }
        try {
            return constructor.newInstance(initArgs);
        } catch (Exception e) {
            throw new IntrospectionException("Unable to create an object of class " + constructor.getDeclaringClass().getName(), e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy