Example usage for org.apache.commons.lang3.reflect ConstructorUtils getMatchingAccessibleConstructor

List of usage examples for org.apache.commons.lang3.reflect ConstructorUtils getMatchingAccessibleConstructor

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect ConstructorUtils getMatchingAccessibleConstructor.

Prototype

public static <T> Constructor<T> getMatchingAccessibleConstructor(final Class<T> cls,
        final Class<?>... parameterTypes) 

Source Link

Document

Finds an accessible constructor with compatible parameters.

This checks all the constructor and finds one with compatible parameters This requires that every parameter is assignable from the given parameter types.

Usage

From source file:gobblin.util.reflection.GobblinConstructorUtils.java

/**
 * Returns a new instance of the <code>cls</code> based on a set of arguments. The method will search for a
 * constructor accepting the first k arguments in <code>args</code> for every k from args.length to 0, and will
 * invoke the first constructor found./* w w  w.  j  a  v  a  2 s .  co  m*/
 *
 * For example, {@link #invokeLongestConstructor}(cls, myString, myInt) will first attempt to create an object with
 * of class <code>cls</code> with constructor <init>(String, int), if it fails it will attempt <init>(String), and
 * finally <init>().
 *
 * @param cls the class to instantiate.
 * @param args the arguments to use for instantiation.
 * @throws ReflectiveOperationException
 */
public static <T> T invokeLongestConstructor(Class<T> cls, Object... args) throws ReflectiveOperationException {

    Class<?>[] parameterTypes = new Class[args.length];
    for (int i = 0; i < args.length; i++) {
        parameterTypes[i] = args[i].getClass();
    }

    for (int i = args.length; i >= 0; i--) {
        if (ConstructorUtils.getMatchingAccessibleConstructor(cls,
                Arrays.copyOfRange(parameterTypes, 0, i)) != null) {
            log.info(String.format("Found accessible constructor for class %s with parameter types %s.", cls,
                    Arrays.toString(Arrays.copyOfRange(parameterTypes, 0, i))));
            return ConstructorUtils.invokeConstructor(cls, Arrays.copyOfRange(args, 0, i));
        }
    }
    throw new NoSuchMethodException(
            String.format("No accessible constructor for class %s with parameters a subset of %s.", cls,
                    Arrays.toString(parameterTypes)));
}

From source file:lite.log.intercept.Modifier.java

public T newInstance(Object... initargs) throws ReflectiveOperationException {
    if (initargs == null)
        return modifiedClazz.newInstance();

    Class<?>[] parameterTypes = new Class[initargs.length];
    for (int i = 0; i < parameterTypes.length; i++) {
        parameterTypes[i] = initargs[i].getClass();
    }/*from   w w w.  j  av  a2s  .co  m*/

    Constructor<T> constructor = ConstructorUtils.getMatchingAccessibleConstructor(modifiedClazz,
            parameterTypes);
    Objects.requireNonNull(constructor, modifiedClazz.getSimpleName()
            + " constructor not found, parameterTypes: " + Arrays.toString(parameterTypes));
    return constructor.newInstance(initargs);
}

From source file:com.opensymphony.xwork2.util.ProxyUtil.java

/**
 * Check whether the given class has a given member.
 * @param clazz the class to check//from   w ww. j ava2s  .co  m
 * @param member the member to check
 */
private static boolean hasMember(Class<?> clazz, Member member) {
    if (member instanceof Method) {
        return null != MethodUtils.getMatchingMethod(clazz, member.getName(),
                ((Method) member).getParameterTypes());
    }
    if (member instanceof Field) {
        return null != FieldUtils.getField(clazz, member.getName(), true);
    }
    if (member instanceof Constructor) {
        return null != ConstructorUtils.getMatchingAccessibleConstructor(clazz,
                ((Constructor) member).getParameterTypes());
    }

    return false;
}

From source file:gobblin.runtime.app.ServiceBasedAppLauncher.java

private void addServicesFromProperties(Properties properties) throws IllegalAccessException,
        InstantiationException, ClassNotFoundException, InvocationTargetException {
    if (properties.containsKey(APP_ADDITIONAL_SERVICES)) {
        for (String serviceClassName : new State(properties).getPropAsSet(APP_ADDITIONAL_SERVICES)) {
            Class<?> serviceClass = Class.forName(serviceClassName);
            if (Service.class.isAssignableFrom(serviceClass)) {
                Service service;//from w  ww.  j  a  va  2 s  .c om
                Constructor<?> constructor = ConstructorUtils.getMatchingAccessibleConstructor(serviceClass,
                        Properties.class);
                if (constructor != null) {
                    service = (Service) constructor.newInstance(properties);
                } else {
                    service = (Service) serviceClass.newInstance();
                }
                addService(service);
            } else {
                throw new IllegalArgumentException(
                        String.format("Class %s specified by %s does not implement %s", serviceClassName,
                                APP_ADDITIONAL_SERVICES, Service.class.getSimpleName()));
            }
        }
    }
}

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 w  w .j  a  v  a  2 s. c  om*/
 * @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.apache.bval.jsr.ApacheValidatorFactory.java

@Privileged
private <F extends MetaBeanFactory> F createMetaBeanFactory(final Class<F> cls) {
    try {//from  w  w  w  .ja  va2s .c o  m
        Constructor<F> c = ConstructorUtils.getMatchingAccessibleConstructor(cls,
                ApacheValidatorFactory.this.getClass());
        if (c != null) {
            return c.newInstance(this);
        }
        c = ConstructorUtils.getMatchingAccessibleConstructor(cls, getClass());
        if (c != null) {
            return c.newInstance(this);
        }
        return cls.newInstance();
    } catch (Exception e) {
        throw new ValidationException(e);
    }
}

From source file:org.apache.gobblin.util.reflection.GobblinConstructorUtils.java

/**
 * Returns a new instance of the <code>cls</code> based on a set of arguments. The method will search for a
 * constructor accepting the first k arguments in <code>args</code> for every k from args.length to 0, and will
 * invoke the first constructor found./*ww w.  jav a 2  s .co  m*/
 *
 * For example, {@link #invokeLongestConstructor}(cls, myString, myInt) will first attempt to create an object with
 * of class <code>cls</code> with constructor <init>(String, int), if it fails it will attempt <init>(String), and
 * finally <init>().
 *
 * @param cls the class to instantiate.
 * @param args the arguments to use for instantiation.
 * @throws ReflectiveOperationException
 */
public static <T> T invokeLongestConstructor(Class<T> cls, Object... args) throws ReflectiveOperationException {

    Class<?>[] parameterTypes = new Class[args.length];
    for (int i = 0; i < args.length; i++) {
        parameterTypes[i] = args[i].getClass();
    }

    for (int i = args.length; i >= 0; i--) {
        if (ConstructorUtils.getMatchingAccessibleConstructor(cls,
                Arrays.copyOfRange(parameterTypes, 0, i)) != null) {
            log.debug(String.format("Found accessible constructor for class %s with parameter types %s.", cls,
                    Arrays.toString(Arrays.copyOfRange(parameterTypes, 0, i))));
            return ConstructorUtils.invokeConstructor(cls, Arrays.copyOfRange(args, 0, i));
        }
    }
    throw new NoSuchMethodException(
            String.format("No accessible constructor for class %s with parameters a subset of %s.", cls,
                    Arrays.toString(parameterTypes)));
}

From source file:org.lenskit.util.reflect.InstanceFactory.java

/**
 * Instance factory calling a constructor with arguments.
 * @param cls The class to instantiate.//from w  w w  .j a v  a2  s. c  o m
 * @param args The arguments.
 * @param <T> The instantiated type.
 * @return An instance factory to produce new instances of {@code cls}.
 */
public static <T> InstanceFactory<T> fromConstructor(Class<? extends T> cls, Object... args) {
    Class[] types = new Class[args.length];
    for (int i = 0; i < args.length; i++) {
        types[i] = args[i].getClass();
    }
    Constructor<? extends T> ctor = ConstructorUtils.getMatchingAccessibleConstructor(cls, types);
    if (ctor != null) {
        return new CtorInstanceFactory<T>(ctor, args);
    } else {
        throw new IllegalArgumentException("no matching constructor for " + cls);
    }
}

From source file:therian.module.SelfContainedTherianModule.java

@SuppressWarnings("rawtypes")
private <O extends Operator> O newInstance(Class<O> c) {
    if (c.isInterface()) {
        return null;
    }//ww w.j ava  2s.  c  o m
    if (Modifier.isAbstract(c.getModifiers())) {
        return null;
    }
    final Class<?>[] paramTypes;
    final Object[] args;
    if (Modifier.isStatic(c.getModifiers())) {
        paramTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
        args = ArrayUtils.EMPTY_OBJECT_ARRAY;
    } else {
        paramTypes = new Class[] { getClass() };
        args = new Object[] { this };
    }
    final Constructor<O> cs = ConstructorUtils.getMatchingAccessibleConstructor(c, paramTypes);
    if (cs == null) {
        return null;
    }
    try {
        return cs.newInstance(args);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}