Example usage for java.lang.reflect Constructor getParameterTypes

List of usage examples for java.lang.reflect Constructor getParameterTypes

Introduction

In this page you can find the example usage for java.lang.reflect Constructor getParameterTypes.

Prototype

@Override
public Class<?>[] getParameterTypes() 

Source Link

Usage

From source file:org.springframework.beans.factory.support.ConstructorResolver.java

protected Constructor<?> getUserDeclaredConstructor(Constructor<?> constructor) {
    Class<?> declaringClass = constructor.getDeclaringClass();
    Class<?> userClass = ClassUtils.getUserClass(declaringClass);
    if (userClass != declaringClass) {
        try {/* ww  w  .  ja v  a2s  .c  o  m*/
            return userClass.getDeclaredConstructor(constructor.getParameterTypes());
        } catch (NoSuchMethodException ex) {
            // No equivalent constructor on user class (superclass)...
            // Let's proceed with the given constructor as we usually would.
        }
    }
    return constructor;
}

From source file:org.springframework.batch.core.jsr.configuration.support.SpringAutowiredAnnotationBeanPostProcessor.java

@Override
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName)
        throws BeansException {
    // Quick check on the concurrent map first, with minimal locking.
    Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
    if (candidateConstructors == null) {
        synchronized (this.candidateConstructorsCache) {
            candidateConstructors = this.candidateConstructorsCache.get(beanClass);
            if (candidateConstructors == null) {
                Constructor<?>[] rawCandidates = beanClass.getDeclaredConstructors();
                List<Constructor<?>> candidates = new ArrayList<Constructor<?>>(rawCandidates.length);
                Constructor<?> requiredConstructor = null;
                Constructor<?> defaultConstructor = null;
                for (Constructor<?> candidate : rawCandidates) {
                    Annotation annotation = findAutowiredAnnotation(candidate);
                    if (annotation != null) {
                        if (requiredConstructor != null) {
                            throw new BeanCreationException("Invalid autowire-marked constructor: " + candidate
                                    + ". Found another constructor with 'required' Autowired annotation: "
                                    + requiredConstructor);
                        }/*from  ww  w .j  av  a 2  s.c o m*/
                        if (candidate.getParameterTypes().length == 0) {
                            throw new IllegalStateException(
                                    "Autowired annotation requires at least one argument: " + candidate);
                        }
                        boolean required = determineRequiredStatus(annotation);
                        if (required) {
                            if (!candidates.isEmpty()) {
                                throw new BeanCreationException("Invalid autowire-marked constructors: "
                                        + candidates
                                        + ". Found another constructor with 'required' Autowired annotation: "
                                        + requiredConstructor);
                            }
                            requiredConstructor = candidate;
                        }
                        candidates.add(candidate);
                    } else if (candidate.getParameterTypes().length == 0) {
                        defaultConstructor = candidate;
                    }
                }
                if (!candidates.isEmpty()) {
                    // Add default constructor to list of optional constructors, as fallback.
                    if (requiredConstructor == null && defaultConstructor != null) {
                        candidates.add(defaultConstructor);
                    }
                    candidateConstructors = candidates.toArray(new Constructor[candidates.size()]);
                } else {
                    candidateConstructors = new Constructor[0];
                }
                this.candidateConstructorsCache.put(beanClass, candidateConstructors);
            }
        }
    }
    return (candidateConstructors.length > 0 ? candidateConstructors : null);
}

From source file:org.apache.empire.db.DBReader.java

/**
 * Returns the result of a query as a list of objects restricted
 * to a maximum number of objects (unless maxCount is -1).
 * /*from w  w w .j a  va 2 s  . c o  m*/
 * @param c the collection to add the objects to
 * @param t the class type of the objects in the list
 * @param maxCount the maximum number of objects
 * 
 * @return the list of T
 */
@SuppressWarnings("unchecked")
public <C extends Collection<T>, T> C getBeanList(C c, Class<T> t, int maxCount) {
    // Check Recordset
    if (rset == null) { // Resultset not available
        throw new ObjectNotValidException(this);
    }
    // Query List
    try {
        // Check whether we can use a constructor
        Class[] paramTypes = new Class[getFieldCount()];
        for (int i = 0; i < colList.length; i++)
            paramTypes[i] = DBExpr.getValueClass(colList[i].getDataType());
        // Find Constructor
        Constructor ctor = findMatchingAccessibleConstructor(t, paramTypes);
        Object[] args = (ctor != null) ? new Object[getFieldCount()] : null;

        // Create a list of beans
        while (moveNext() && maxCount != 0) { // Create bean an init
            if (ctor != null) { // Use Constructor
                Class<?>[] ctorParamTypes = ctor.getParameterTypes();
                for (int i = 0; i < getFieldCount(); i++)
                    args[i] = ObjectUtils.convert(ctorParamTypes[i], getValue(i));
                T bean = (T) ctor.newInstance(args);
                c.add(bean);
            } else { // Use Property Setters
                T bean = t.newInstance();
                getBeanProperties(bean);
                c.add(bean);
            }
            // Decrease count
            if (maxCount > 0)
                maxCount--;
        }
        // done
        return c;
    } catch (InvocationTargetException e) {
        throw new BeanInstantiationException(t, e);
    } catch (IllegalAccessException e) {
        throw new BeanInstantiationException(t, e);
    } catch (InstantiationException e) {
        throw new BeanInstantiationException(t, e);
    }
}

From source file:org.talend.daikon.properties.PropertiesImpl.java

@Override
public NamedThing createPropertyInstance(NamedThing otherProp) throws ReflectiveOperationException {
    NamedThing thisProp = null;/* w  w w. j av  a  2  s.c o m*/
    Class<? extends NamedThing> otherClass = otherProp.getClass();
    if (Property.class.isAssignableFrom(otherClass)) {
        Property<?> otherPy = (Property<?>) otherProp;
        Constructor<? extends NamedThing> c = otherClass.getDeclaredConstructor(String.class, String.class);
        c.setAccessible(true);
        thisProp = c.newInstance(otherPy.getType(), otherPy.getName());
    } else if (Properties.class.isAssignableFrom(otherClass)) {
        // Look for single arg String, but an inner class will have a Properties as first arg
        Constructor<?>[] constructors = otherClass.getConstructors();
        for (Constructor<?> c : constructors) {
            Class<?> pts[] = c.getParameterTypes();
            c.setAccessible(true);
            if (pts.length == 1 && String.class.isAssignableFrom(pts[0])) {
                thisProp = (NamedThing) c.newInstance(otherProp.getName());
                break;
            }
            if (pts.length == 2 && Properties.class.isAssignableFrom(pts[0])
                    && String.class.isAssignableFrom(pts[1])) {
                thisProp = (NamedThing) c.newInstance(this, otherProp.getName());
                break;
            }
        }
        if (thisProp == null) {
            TalendRuntimeException.unexpectedException(
                    "Failed to find a proper constructor in Properties : " + otherClass.getName());
        }
    } else {
        TalendRuntimeException.unexpectedException(
                "Unexpected property class: " + otherProp.getClass() + " prop: " + otherProp);
    }
    return thisProp;
}

From source file:org.kepler.objectmanager.ActorMetadata.java

/**
 * createInstance. creates an instance of a class object. taken from
 * ptolemy's MomlParser class. modified for this application.
 * //from  ww  w.  j a va 2  s . c  o  m
 * @param newClass
 *@param arguments
 *@return TypedAtomicActor
 *@exception Exception
 */
public static NamedObj createInstance(Class<?> newClass, Object[] arguments) throws Exception {
    if (isDebugging)
        log.debug("createInstance(" + newClass + "," + arguments + ")");
    Constructor<?>[] constructors = newClass.getConstructors();
    for (int i = 0; i < constructors.length; i++) {
        Constructor<?> constructor = constructors[i];
        Class<?>[] parameterTypes = constructor.getParameterTypes();

        for (int j = 0; j < parameterTypes.length; j++) {
            Class<?> c = parameterTypes[j];
            if (isDebugging)
                log.debug(c.getName());
        }

        if (parameterTypes.length != arguments.length) {
            continue;
        }

        boolean match = true;

        for (int j = 0; j < parameterTypes.length; j++) {
            if (!(parameterTypes[j].isInstance(arguments[j]))) {
                match = false;
                break;
            }
        }

        if (match) {
            NamedObj newEntity = (NamedObj) constructor.newInstance(arguments);
            return newEntity;
        }
    }

    // If we get here, then there is no matching constructor.
    // Generate a StringBuffer containing what we were looking for.
    StringBuffer argumentBuffer = new StringBuffer();

    for (int i = 0; i < arguments.length; i++) {
        argumentBuffer.append(arguments[i].getClass() + " = \"" + arguments[i].toString() + "\"");

        if (i < (arguments.length - 1)) {
            argumentBuffer.append(", ");
        }
    }

    throw new Exception("Cannot find a suitable constructor (" + arguments.length + " args) (" + argumentBuffer
            + ") for '" + newClass.getName() + "'");
}

From source file:com.zigabyte.stock.stratplot.StrategyPlotter.java

/** Loads strategy class and creates instance by calling constructor.
    @param strategyText contains full class name followed by
    parameter list for constructor.  Constructor parameters may be
    int, double, boolean, String.  Constructor parameters are parsed by
    splitting on commas and trimming whitespace.
    <pre>/*w  w w . ja  v a 2  s . c  o  m*/
    mypkg.MyStrategy(12, -345.67, true, false, Alpha Strategy)
    </pre>
**/
protected TradingStrategy loadStrategy(String strategyText)
        throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
        ExceptionInInitializerError, InstantiationException, InvocationTargetException {
    Pattern strategyPattern = // matches full.class.Name(args...)
            Pattern.compile("^([A-Za-z](?:[A-Za-z0-9_.]*))\\s*[(](.*)[)]$");
    Matcher matcher = strategyPattern.matcher(strategyText);
    if (!matcher.matches())
        throw new IllegalArgumentException(
                "Bad Strategy: " + strategyText + "\n" + "Expected: full.class.name(-123.45, 67, true, false)");

    final String strategyClassName = matcher.group(1).trim();
    String parameters[] = matcher.group(2).split(",");

    // clean parameters
    for (int i = 0; i < parameters.length; i++)
        parameters[i] = parameters[i].trim();
    if (parameters.length == 1 && parameters[0].length() == 0)
        parameters = new String[] {}; // 0 parameters

    // build classpath
    String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator);
    ArrayList<URL> classPathURLs = new ArrayList<URL>();
    for (int i = 0; i < classPath.length; i++) {
        String path = classPath[i];
        if (".".equals(path))
            path = System.getProperty("user.dir");
        path = path.replace(File.separatorChar, '/');
        if (!path.endsWith("/") && !path.endsWith(".jar"))
            path += "/";
        try {
            classPathURLs.add(new File(path).toURL());
        } catch (MalformedURLException e) {
            // bad directory in class path, skip
        }
    }
    final String strategyPackagePrefix = strategyClassName.substring(0,
            Math.max(0, strategyClassName.lastIndexOf('.') + 1));
    ClassLoader loader = new URLClassLoader(classPathURLs.toArray(new URL[] {}),
            this.getClass().getClassLoader()) {
        /** Don't search parent for classes with strategyPackagePrefix.
            Exception: interface TradingStrategy **/
        protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {
            Class<?> loadedClass = findLoadedClass(className);
            if (loadedClass != null)
                return loadedClass;
            if (!className.startsWith(strategyPackagePrefix)
                    || className.equals(TradingStrategy.class.getName())) {
                loadedClass = this.getParent().loadClass(className);
                if (loadedClass != null)
                    return loadedClass;
            }
            loadedClass = findClass(className);
            if (loadedClass != null) {
                if (resolve)
                    resolveClass(loadedClass);
                return loadedClass;
            } else
                throw new ClassNotFoundException(className);
        }
    };
    // load class.  Throws ClassNotFoundException if not found.
    Class<?> strategyClass = loader.loadClass(strategyClassName);

    // Make sure it is a TradingStrategy.
    if (!TradingStrategy.class.isAssignableFrom(strategyClass))
        throw new ClassCastException(strategyClass.getName() + " does not implement TradingStrategy");

    // Find constructor compatible with parameters
    Constructor[] constructors = strategyClass.getConstructors();
    findConstructor: for (Constructor constructor : constructors) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if (parameterTypes.length != parameters.length)
            continue;
        Object[] values = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            if (boolean.class.equals(parameterTypes[i])) {
                String parameter = parameters[i].toLowerCase();
                if ("false".equals(parameter))
                    values[i] = Boolean.FALSE;
                else if ("true".equals(parameter))
                    values[i] = Boolean.TRUE;
                else
                    continue findConstructor;
            } else if (int.class.equals(parameterTypes[i])) {
                try {
                    values[i] = new Integer(parameters[i]);
                } catch (NumberFormatException e) {
                    continue findConstructor;
                }
            } else if (double.class.equals(parameterTypes[i])) {
                try {
                    values[i] = new Double(parameters[i]);
                } catch (NumberFormatException e) {
                    continue findConstructor;
                }
            } else if (String.class.equals(parameterTypes[i])) {
                values[i] = parameters[i];
            } else
                continue findConstructor; // unsupported parameter type, skip
        }
        // all values matched types, so create instance
        return (TradingStrategy) constructor.newInstance(values);
    }
    throw new NoSuchMethodException(strategyText);
}

From source file:org.kuali.rice.krad.service.impl.DocumentServiceImpl.java

private DocumentEvent generateKualiDocumentEvent(Document document, Class<? extends DocumentEvent> eventClass)
        throws ConfigurationException {
    String potentialErrorMessage = "Found error trying to generate Kuali Document Event using event class '"
            + eventClass.getName() + "' for document " + document.getDocumentNumber();

    try {//from   ww  w. j a  v a 2s . c o  m
        Constructor<?> usableConstructor = null;
        List<Object> paramList = new ArrayList<Object>();
        for (Constructor<?> currentConstructor : eventClass.getConstructors()) {
            for (Class<?> parameterClass : currentConstructor.getParameterTypes()) {
                if (Document.class.isAssignableFrom(parameterClass)) {
                    usableConstructor = currentConstructor;
                    paramList.add(document);
                } else {
                    paramList.add(null);
                }
            }
            if (KRADUtils.isNotNull(usableConstructor)) {
                break;
            }
        }
        if (usableConstructor == null) {
            throw new RuntimeException("Cannot find a constructor for class '" + eventClass.getName()
                    + "' that takes in a document parameter");
        }
        return (DocumentEvent) usableConstructor.newInstance(paramList.toArray());
    } catch (SecurityException e) {
        throw new ConfigurationException(potentialErrorMessage, e);
    } catch (IllegalArgumentException e) {
        throw new ConfigurationException(potentialErrorMessage, e);
    } catch (InstantiationException e) {
        throw new ConfigurationException(potentialErrorMessage, e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationException(potentialErrorMessage, e);
    } catch (InvocationTargetException e) {
        throw new ConfigurationException(potentialErrorMessage, e);
    }
}

From source file:com.joliciel.talismane.machineLearning.features.AbstractFeatureParser.java

/**
 * Get the features corresponding to a particular descriptor by performing
 * reflection on the corresponding feature class to be instantiated.
 * @param descriptor//from   w ww  . j a  va2s .c o m
 * @param featureClass
 * @return
 */
final List<Feature<T, ?>> getFeatures(FunctionDescriptor descriptor,
        @SuppressWarnings("rawtypes") Class<? extends Feature> featureClass,
        FunctionDescriptor topLevelDescriptor) {
    if (featureClass == null)
        throw new FeatureSyntaxException("No class provided for", descriptor, topLevelDescriptor);

    List<Feature<T, ?>> features = new ArrayList<Feature<T, ?>>();
    int i = 0;
    List<List<Object>> argumentLists = new ArrayList<List<Object>>();
    List<Object> initialArguments = new ArrayList<Object>();
    argumentLists.add(initialArguments);

    for (FunctionDescriptor argumentDescriptor : descriptor.getArguments()) {
        List<List<Object>> newArgumentLists = new ArrayList<List<Object>>();
        for (List<Object> arguments : argumentLists) {
            if (!argumentDescriptor.isFunction()) {
                Object literal = argumentDescriptor.getObject();
                Object convertedObject = literal;
                if (literal instanceof String) {
                    StringLiteralFeature<T> stringLiteralFeature = new StringLiteralFeature<T>(
                            (String) literal);
                    convertedObject = stringLiteralFeature;
                } else if (literal instanceof Boolean) {
                    BooleanLiteralFeature<T> booleanLiteralFeature = new BooleanLiteralFeature<T>(
                            (Boolean) literal);
                    convertedObject = booleanLiteralFeature;
                } else if (literal instanceof Double) {
                    DoubleLiteralFeature<T> doubleLiteralFeature = new DoubleLiteralFeature<T>(
                            (Double) literal);
                    convertedObject = doubleLiteralFeature;
                } else if (literal instanceof Integer) {
                    IntegerLiteralFeature<T> integerLiteralFeature = new IntegerLiteralFeature<T>(
                            (Integer) literal);
                    convertedObject = integerLiteralFeature;
                } else {
                    // do nothing - this was some sort of other object added by getModifiedDescriptors that should
                    // be handled as is.
                }
                arguments.add(convertedObject);
                newArgumentLists.add(arguments);

            } else {
                List<Feature<T, ?>> featureArguments = this.parseInternal(argumentDescriptor,
                        topLevelDescriptor);
                // a single argument descriptor could produce multiple arguments
                // e.g. when a function with an array argument is mapped onto multiple function calls
                for (Feature<T, ?> featureArgument : featureArguments) {
                    List<Object> newArguments = new ArrayList<Object>(arguments);
                    newArguments.add(featureArgument);
                    newArgumentLists.add(newArguments);
                }
            } // function or object?

        } // next argument list (under construction from original arguments)
        argumentLists = newArgumentLists;
    } // next argument

    for (List<Object> originalArgumentList : argumentLists) {
        // add the argument types (i.e. classes)
        // and convert arrays to multiple constructor calls
        List<Object[]> argumentsList = new ArrayList<Object[]>();
        argumentsList.add(new Object[originalArgumentList.size()]);

        Class<?>[] argumentTypes = new Class<?>[originalArgumentList.size()];
        List<Object[]> newArgumentsList = new ArrayList<Object[]>();
        for (i = 0; i < originalArgumentList.size(); i++) {
            Object arg = originalArgumentList.get(i);

            if (arg.getClass().isArray()) {
                // arrays represent multiple constructor calls
                Object[] argArray = (Object[]) arg;
                for (Object oneArg : argArray) {
                    for (Object[] arguments : argumentsList) {
                        Object[] newArguments = arguments.clone();
                        newArguments[i] = oneArg;
                        newArgumentsList.add(newArguments);
                    }
                }
                argumentTypes[i] = arg.getClass().getComponentType();
            } else {
                for (Object[] myArguments : argumentsList) {
                    newArgumentsList.add(myArguments);
                    myArguments[i] = arg;
                }
                argumentTypes[i] = arg.getClass();
            }
            argumentsList = newArgumentsList;
            newArgumentsList = new ArrayList<Object[]>();
        } // next argument

        @SuppressWarnings("rawtypes")
        Constructor<? extends Feature> constructor = null;
        MONITOR.startTask("findContructor");
        try {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(featureClass, argumentTypes);

            if (constructor == null) {
                Constructor<?>[] constructors = featureClass.getConstructors();

                // check if there's a variable argument constructor
                for (Constructor<?> oneConstructor : constructors) {
                    Class<?>[] parameterTypes = oneConstructor.getParameterTypes();

                    if (parameterTypes.length >= 1 && argumentsList.size() == 1
                            && argumentsList.get(0).length >= parameterTypes.length) {
                        Object[] arguments = argumentsList.get(0);
                        Class<?> parameterType = parameterTypes[parameterTypes.length - 1];
                        if (parameterType.isArray()) {
                            // assume it's a variable-argument constructor
                            // build the argument for this constructor
                            // find a common type for all of the arguments.
                            Object argument = arguments[parameterTypes.length - 1];
                            Class<?> clazz = null;
                            if (argument instanceof StringFeature)
                                clazz = StringFeature.class;
                            else if (argument instanceof BooleanFeature)
                                clazz = BooleanFeature.class;
                            else if (argument instanceof DoubleFeature)
                                clazz = DoubleFeature.class;
                            else if (argument instanceof IntegerFeature)
                                clazz = IntegerFeature.class;
                            else if (argument instanceof StringCollectionFeature)
                                clazz = StringFeature.class;
                            else {
                                // no good, can't make arrays of this type
                                continue;
                            }

                            Object[] argumentArray = (Object[]) Array.newInstance(clazz,
                                    (arguments.length - parameterTypes.length) + 1);
                            int j = 0;
                            for (int k = parameterTypes.length - 1; k < arguments.length; k++) {
                                Object oneArgument = arguments[k];
                                if (oneArgument instanceof StringCollectionFeature) {
                                    @SuppressWarnings("unchecked")
                                    StringCollectionFeature<T> stringCollectionFeature = (StringCollectionFeature<T>) oneArgument;
                                    StringCollectionFeatureProxy<T> proxy = new StringCollectionFeatureProxy<T>(
                                            stringCollectionFeature);
                                    oneArgument = proxy;
                                }
                                if (!clazz.isAssignableFrom(oneArgument.getClass())) {
                                    throw new FeatureSyntaxException(
                                            "Mismatched array types: " + clazz.getSimpleName() + ", "
                                                    + oneArgument.getClass().getSimpleName(),
                                            descriptor, topLevelDescriptor);
                                }
                                argumentArray[j++] = oneArgument;
                            } // next argument

                            Class<?>[] argumentTypesWithArray = new Class<?>[parameterTypes.length];
                            for (int k = 0; k < parameterTypes.length - 1; k++) {
                                Object oneArgument = arguments[k];
                                argumentTypesWithArray[k] = oneArgument.getClass();
                            }
                            argumentTypesWithArray[argumentTypesWithArray.length - 1] = argumentArray
                                    .getClass();
                            constructor = ConstructorUtils.getMatchingAccessibleConstructor(featureClass,
                                    argumentTypesWithArray);

                            if (constructor != null) {
                                argumentsList = new ArrayList<Object[]>();
                                Object[] argumentsWithArray = new Object[parameterTypes.length];
                                for (int k = 0; k < parameterTypes.length - 1; k++) {
                                    Object oneArgument = arguments[k];
                                    argumentsWithArray[k] = oneArgument;
                                }
                                argumentsWithArray[parameterTypes.length - 1] = argumentArray;
                                argumentsList.add(argumentsWithArray);
                                break;
                            }
                        } // constructor takes an array
                    } // exactly one parameter for constructor
                } // next constructor

                if (constructor == null) {
                    // See if various conversions allow us to find a constructor
                    // Integer to Double
                    // StringCollectionFeature to StringFeature
                    for (Constructor<?> oneConstructor : constructors) {
                        Class<?>[] parameterTypes = oneConstructor.getParameterTypes();
                        boolean isMatchingConstructor = false;
                        List<Integer> intParametersToConvert = new ArrayList<Integer>();
                        List<Integer> stringCollectionParametersToConvert = new ArrayList<Integer>();
                        List<Integer> customParametersToConvert = new ArrayList<Integer>();
                        if (parameterTypes.length == argumentTypes.length) {
                            int j = 0;
                            isMatchingConstructor = true;

                            for (Class<?> parameterType : parameterTypes) {
                                if (parameterType.isAssignableFrom(argumentTypes[j])
                                        && !StringCollectionFeature.class.isAssignableFrom(argumentTypes[j])) {
                                    // nothing to do here
                                } else if (parameterType.equals(DoubleFeature.class)
                                        && IntegerFeature.class.isAssignableFrom(argumentTypes[j])) {
                                    intParametersToConvert.add(j);
                                } else if ((parameterType.equals(StringFeature.class)
                                        || parameterType.equals(Feature.class))
                                        && StringCollectionFeature.class.isAssignableFrom(argumentTypes[j])) {
                                    stringCollectionParametersToConvert.add(j);
                                } else if (this.canConvert(parameterType, argumentTypes[j])) {
                                    customParametersToConvert.add(j);
                                } else {
                                    isMatchingConstructor = false;
                                    break;
                                }
                                j++;
                            }
                        }
                        if (isMatchingConstructor) {
                            @SuppressWarnings({ "rawtypes", "unchecked" })
                            Constructor<? extends Feature> matchingConstructor = (Constructor<? extends Feature>) oneConstructor;
                            constructor = matchingConstructor;

                            for (Object[] myArguments : argumentsList) {
                                for (int indexToConvert : intParametersToConvert) {
                                    @SuppressWarnings("unchecked")
                                    IntegerFeature<T> integerFeature = (IntegerFeature<T>) myArguments[indexToConvert];
                                    IntegerToDoubleFeature<T> intToDoubleFeature = new IntegerToDoubleFeature<T>(
                                            integerFeature);
                                    myArguments[indexToConvert] = intToDoubleFeature;
                                }
                                for (int indexToConvert : stringCollectionParametersToConvert) {
                                    @SuppressWarnings("unchecked")
                                    StringCollectionFeature<T> stringCollectionFeature = (StringCollectionFeature<T>) myArguments[indexToConvert];
                                    StringCollectionFeatureProxy<T> proxy = new StringCollectionFeatureProxy<T>(
                                            stringCollectionFeature);
                                    myArguments[indexToConvert] = proxy;
                                }
                                for (int indexToConvert : customParametersToConvert) {
                                    @SuppressWarnings("unchecked")
                                    Feature<T, ?> argumentToConvert = (Feature<T, ?>) myArguments[indexToConvert];
                                    Feature<T, ?> customArgument = this
                                            .convertArgument(parameterTypes[indexToConvert], argumentToConvert);
                                    myArguments[indexToConvert] = customArgument;
                                    customArgument.addArgument(argumentToConvert);
                                }
                            }
                            break;
                        } // found a matching constructor
                    } // next possible constructor
                } // still haven't found a constructor, what next?
            } // didn't find a constructor yet
        } finally {
            MONITOR.endTask("findContructor");
        }

        if (constructor == null)
            throw new NoConstructorFoundException("No constructor found for " + descriptor.getFunctionName()
                    + " (" + featureClass.getName() + ") matching the arguments provided", descriptor,
                    topLevelDescriptor);

        for (Object[] myArguments : argumentsList) {
            @SuppressWarnings("rawtypes")
            Feature feature;
            try {
                feature = constructor.newInstance(myArguments);
            } catch (IllegalArgumentException e) {
                throw new RuntimeException(e);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }

            @SuppressWarnings("unchecked")
            Feature<T, ?> genericFeature = (Feature<T, ?>) feature;
            this.injectDependencies(feature);
            if (genericFeature instanceof ExternalResourceFeature) {
                if (this.getExternalResourceFinder() == null) {
                    throw new JolicielException("No external resource finder set.");
                }
                @SuppressWarnings("unchecked")
                ExternalResourceFeature<T> externalResourceFeature = (ExternalResourceFeature<T>) genericFeature;
                externalResourceFeature.setExternalResourceFinder(this.getExternalResourceFinder());
            } else if (genericFeature instanceof ExternalResourceDoubleFeature) {
                if (this.getExternalResourceFinder() == null) {
                    throw new JolicielException("No external resource finder set.");
                }
                @SuppressWarnings("unchecked")
                ExternalResourceDoubleFeature<T> externalResourceFeature = (ExternalResourceDoubleFeature<T>) genericFeature;
                externalResourceFeature.setExternalResourceFinder(this.getExternalResourceFinder());
            } else if (genericFeature instanceof MultivaluedExternalResourceFeature) {
                if (this.getExternalResourceFinder() == null) {
                    throw new JolicielException("No external resource finder set.");
                }
                @SuppressWarnings("unchecked")
                MultivaluedExternalResourceFeature<T> externalResourceFeature = (MultivaluedExternalResourceFeature<T>) genericFeature;
                externalResourceFeature.setExternalResourceFinder(this.getExternalResourceFinder());
            }

            // add this feature's arguments
            for (Object argument : myArguments) {
                if (argument instanceof Feature[]) {
                    @SuppressWarnings("unchecked")
                    Feature<T, ?>[] featureArray = (Feature<T, ?>[]) argument;
                    for (Feature<T, ?> oneFeature : featureArray) {
                        genericFeature.addArgument(oneFeature);
                    }
                } else {
                    @SuppressWarnings("unchecked")
                    Feature<T, ?> featureArgument = (Feature<T, ?>) argument;
                    genericFeature.addArgument(featureArgument);
                }
            }

            Feature<T, ?> convertedFeature = this.convertFeature(genericFeature);
            features.add(convertedFeature);
        } // next internal argument list
    } // next argument list
    return features;
}

From source file:org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.java

/**
 * @param constr/*from  ww w .  j a v a  2  s .  c  o m*/
 * @param tlContext
 * @param leaveEncoded
 * @param jaxRsProviders
 * @param extensionBackwardMapping
 * @param paramsAllowed
 * @param logger
 * @param allMustBeAvailable
 * @throws MissingAnnotationException
 * @throws IllegalTypeException
 *             if one of the parameters contains a &#64;{@link Context} on
 *             an type that must not be annotated with &#64;{@link Context}.
 * @throws IllegalPathParamTypeException
 */
public ParameterList(Constructor<?> constr, ThreadLocalizedContext tlContext, boolean leaveEncoded,
        JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, boolean paramsAllowed,
        Logger logger, boolean allMustBeAvailable)
        throws MissingAnnotationException, IllegalTypeException, IllegalPathParamTypeException {
    this(constr.getParameterTypes(), constr.getGenericParameterTypes(), constr.getParameterAnnotations(),
            tlContext, leaveEncoded, jaxRsProviders, extensionBackwardMapping, paramsAllowed, false, logger,
            allMustBeAvailable);
}

From source file:org.apache.myfaces.config.FacesConfigurator.java

/**
 * A mapper for the handful of system listener defaults
 * since every default mapper has the source type embedded
 * in the constructor we can rely on introspection for the
 * default mapping//from   www  . j a  va 2 s.  c  om
 *
 * @param systemEventClass the system listener class which has to be checked
 * @return
 */
String getDefaultSourcClassForSystemEvent(Class systemEventClass) {
    Constructor[] constructors = systemEventClass.getConstructors();
    for (Constructor constr : constructors) {
        Class[] parms = constr.getParameterTypes();
        if (parms == null || parms.length != 1) {
            //for standard types we have only one parameter representing the type
            continue;
        }
        return parms[0].getName();
    }
    log.warning("The SystemEvent source type for " + systemEventClass.getName()
            + " could not be detected, either register it manually or use a constructor argument "
            + "for auto detection, defaulting now to java.lang.Object");
    return "java.lang.Object";
}