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

se.hiq.oss.commons.reflection.util.ConstructorUtils Maven / Gradle / Ivy

The newest version!
package se.hiq.oss.commons.reflection.util;

import java.lang.reflect.Constructor;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import se.hiq.oss.commons.reflection.filter.ConstructorFilter;

/**
 * Utility class for creating object instances using Reflection Based Construction.
 *
 * @author rikardwi
 **/
public final class ConstructorUtils {

    private ConstructorUtils() {
    }

    /**
     * Returns set of constructors that matches the filter parameter.
     *
     * @param target Class to get constructor for.
     * @param filter Filter to apply.
     * @param     Type of constructor.
     *
     * @return constructors that matches the filter parameter.
     * @throws IllegalArgumentException if ofType does not match the target class.
     **/
    @SuppressWarnings("unchecked")
    public static  Set> findConstructors(Class target, ConstructorFilter filter) {

        Set> cons = new HashSet>();
        Constructor[] constructors = (Constructor[]) target.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            if (filter.apply(constructor)) {
                cons.add(constructor);
            }
        }
        return cons;
    }


    /**
     * Returns the first constructor found that matches the filter parameter.
     *
     * @param target Class to get constructor for.
     * @param filter Filter to apply.
     * @param     Type of constructor.
     *
     * @return the first constructor found that matches the filter parameter.
     * @throws IllegalArgumentException if ofType does not match the target class.
     *                                  or no constructor is found matching the filter.
     **/
    public static  Constructor findFirstConstructor(Class target, ConstructorFilter filter) {

        Set> cons = findConstructors(target, filter);
        if (cons.isEmpty()) {
            throw new IllegalArgumentException("No constructor found for " + target.getName() + " matching filter: " + filter.describe());
        }
        return cons.iterator().next();
    }




    /**
     * Creates and returns a new instance of class with name className, loading the class and using the default constructor.
     *
     * @param        Type of instance
     * @param className Name of class
     * @param ofType    Type of class
     *
     * @return a new instance of class loaded from className.
     * @throws IllegalStateException if className could not be loaded or if that class does not have a default constructor
     *                               or if the loaded class is not of the supplied type (ofType).
     */
    public static  T newInstance(String className, Class ofType) throws IllegalStateException {
        return newInstance(className, ofType, new Class[]{}, new Object[]{});
    }

    /**
     * Returns a new object of className. The objected is casted to the ofType,
     * which is either super class or interface of the className class.
     *
     * @param className         Name of the class to instanciate an object of
     * @param ofType            An super class or interface of the className class.
     * @param constructorParams Constructor parameter types
     * @param constructorArgs   Constructor arguments to use when creating a new instance
     * @param                Type of instance.
     *
     * @return A new instance of class with name className casted to the ofType class.
     * @throws IllegalStateException if className could not be loaded or if that class does not have a matching constructor
     *                               to the constructorParam or if the loaded class is not of the supplied type (ofType).
     **/
    @SuppressWarnings("unchecked")
    public static  T newInstance(String className, Class ofType, Class[] constructorParams, Object... constructorArgs) {
        try {
            Class clazz = Class.forName(className);
            Constructor constructor = clazz.getConstructor(constructorParams);
            return ofType.cast(constructor.newInstance(constructorArgs));
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Could not create new instamce of class " + className, e);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            String errorMessage = "Could not create new instamce of class " + className + " using ";
            if (constructorParams.length == 0) {
                errorMessage += "default constructor.";
            } else {
                errorMessage += "constructor with parameters " + StringUtils.join(constructorArgs, ", ") + ".";
            }
            throw new IllegalStateException(errorMessage, e);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy