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.robobinding.util.ConstructorUtils.java

/**
 * <p>/* w w  w .  j ava2  s.  c  om*/
 * Finds an accessible constructor with compatible parameters.
 * </p>
 * 
 * <p>
 * This checks all the constructor and finds one with compatible parameters
 * This requires that every parameter is assignable from the given parameter
 * types. This is a more flexible search than the normal exact matching
 * algorithm.
 * </p>
 * 
 * <p>
 * First it checks if there is a constructor matching the exact signature.
 * If not then all the constructors of the class are checked to see if their
 * signatures are assignment compatible with the parameter types. The first
 * assignment compatible matching constructor is returned.
 * </p>
 * 
 * @param <T>
 *            the constructor type
 * @param cls
 *            the class to find a constructor for, not null
 * @param parameterTypes
 *            find method with compatible parameters
 * @return the constructor, null if no matching accessible constructor found
 */
public static <T> Constructor<T> getMatchingAccessibleConstructor(final Class<T> cls,
        final Class<?>... parameterTypes) {
    // see if we can find the constructor directly
    // most of the time this works and it's much faster
    try {
        final Constructor<T> ctor = cls.getConstructor(parameterTypes);
        MemberUtils.setAccessibleWorkaround(ctor);
        return ctor;
    } catch (final NoSuchMethodException e) { // NOPMD - Swallow
    }
    Constructor<T> result = null;
    /*
     * (1) Class.getConstructors() is documented to return Constructor<T> so
     * as long as the array is not subsequently modified, everything's fine.
     */
    final Constructor<?>[] ctors = cls.getConstructors();

    // return best match:
    for (Constructor<?> ctor : ctors) {
        // compare parameters
        if (ClassUtils.isAssignable(parameterTypes, ctor.getParameterTypes(), true)) {
            // get accessible version of constructor
            ctor = getAccessibleConstructor(ctor);
            if (ctor != null) {
                MemberUtils.setAccessibleWorkaround(ctor);
                if (result == null || MemberUtils.compareParameterTypes(ctor.getParameterTypes(),
                        result.getParameterTypes(), parameterTypes) < 0) {
                    // temporary variable for annotation, see comment above
                    // (1)
                    @SuppressWarnings("unchecked")
                    final Constructor<T> constructor = (Constructor<T>) ctor;
                    result = constructor;
                }
            }
        }
    }
    return result;
}

From source file:adalid.core.XS1.java

static Class<?> getConstructorParameterType(Class<?> wrapper, Class<?> wrappable) {
    Class<?> parameterType = null;
    Constructor<?>[] constructors = wrapper.getConstructors();
    for (Constructor<?> constructor : constructors) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if (parameterTypes.length == 1 && parameterTypes[0].isAssignableFrom(wrappable)) {
            if (parameterType == null || parameterType.isAssignableFrom(parameterTypes[0])) {
                parameterType = parameterTypes[0];
            }//from ww  w .  j a va2s. c  o m
        }
    }
    return parameterType;
}

From source file:com.kaching.platform.converters.ConstructorAnalysis.java

/**
 * Produces an assignment or field names to values or fails.
 * @throws IllegalConstructorException/*ww w.j a  v a  2s  .  co m*/
 */
static AnalysisResult analyse(Class<?> klass, Constructor<?> constructor) throws IOException {
    Class<?>[] parameterTypes = constructor.getParameterTypes();
    InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class");
    if (in == null) {
        throw new IllegalArgumentException(format("can not find bytecode for %s", klass));
    }
    return analyse(in, klass.getName().replace('.', '/'), klass.getSuperclass().getName().replace('.', '/'),
            parameterTypes);
}

From source file:org.jenkinsci.plugins.workflow.structs.DescribableHelper.java

@SuppressWarnings("unchecked")
private static <T> Constructor<T> findConstructor(Class<? extends T> clazz, int length) {
    try { // may work without this, but only if the JVM happens to return the right overload first
        if (clazz == ParametersDefinitionProperty.class && length == 1) { // TODO pending core fix
            return (Constructor<T>) ParametersDefinitionProperty.class.getConstructor(List.class);
        }//from   www  .ja v  a 2s  .  c  om
    } catch (NoSuchMethodException x) {
        throw new AssertionError(x);
    }
    Constructor<T>[] ctrs = (Constructor<T>[]) clazz.getConstructors();
    for (Constructor<T> c : ctrs) {
        if (c.getAnnotation(DataBoundConstructor.class) != null) {
            if (c.getParameterTypes().length != length) {
                throw new IllegalArgumentException(c
                        + " has @DataBoundConstructor but it doesn't match with your .stapler file. Try clean rebuild");
            }
            return c;
        }
    }
    for (Constructor<T> c : ctrs) {
        if (c.getParameterTypes().length == length) {
            return c;
        }
    }
    throw new IllegalArgumentException(clazz + " does not have a constructor with " + length + " arguments");
}

From source file:org.killbill.billing.client.KillBillHttpClient.java

private static <T> T createEmptyResult(final Class<T> clazz) {// Return empty list for KillBillObjects instead of null for convenience
    if (Iterable.class.isAssignableFrom(clazz)) {
        for (final Constructor constructor : clazz.getConstructors()) {
            if (constructor.getParameterTypes().length == 0) {
                try {
                    return clazz.cast(constructor.newInstance());
                } catch (final InstantiationException e) {
                    return null;
                } catch (final IllegalAccessException e) {
                    return null;
                } catch (final InvocationTargetException e) {
                    return null;
                }/*from  w w w.  j  a  va2s  .  c  o m*/
            }
        }
        return null;
    } else {
        return null;
    }
}

From source file:org.mycore.common.MCRUtils.java

@SafeVarargs
public static Exception unwrapExCeption(Exception e, Class<? extends Exception>... classes) {
    if (classes.length == 0) {
        return e;
    }/*from w w w.  ja v  a 2s  .  c o  m*/
    Class<? extends Exception> mainExceptionClass = classes[0];
    Throwable check = e;
    for (Class<? extends Exception> instChk : classes) {
        if (instChk.isInstance(check)) {
            return (Exception) check;
        }
        check = check.getCause();
        if (check == null) {
            break;
        }
    }
    @SuppressWarnings("unchecked")
    Constructor<? extends Exception>[] constructors = (Constructor<? extends Exception>[]) mainExceptionClass
            .getConstructors();
    for (Constructor<? extends Exception> c : constructors) {
        Class<?>[] parameterTypes = c.getParameterTypes();
        try {
            if (parameterTypes.length == 0) {
                Exception exception = c.newInstance((Object[]) null);
                exception.initCause(e);
                return exception;
            }
            if (parameterTypes.length == 1 && parameterTypes[0].isAssignableFrom(mainExceptionClass)) {
                return c.newInstance(e);
            }
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException ex) {
            LOGGER.warn("Exception while initializing exception " + mainExceptionClass.getCanonicalName(), ex);
            return e;
        }
    }
    LOGGER.warn("Could not instanciate Exception " + mainExceptionClass.getCanonicalName());
    return e;
}

From source file:de.escalon.hypermedia.spring.uber.UberUtils.java

/**
 * Renders input fields for bean properties of bean to add or update or patch.
 *
 * @param uberFields/*  ww  w . j  a v  a2  s .  c  o  m*/
 *         to add to
 * @param beanType
 *         to render
 * @param annotatedParameters
 *         which describes the method
 * @param annotatedParameter
 *         which requires the bean
 * @param currentCallValue
 *         sample call value
 */
private static void recurseBeanCreationParams(List<UberField> uberFields, Class<?> beanType,
        ActionDescriptor annotatedParameters, ActionInputParameter annotatedParameter, Object currentCallValue,
        String parentParamName, Set<String> knownFields) {
    // TODO collection, map and object node creation are only describable by an annotation, not via type reflection
    if (ObjectNode.class.isAssignableFrom(beanType) || Map.class.isAssignableFrom(beanType)
            || Collection.class.isAssignableFrom(beanType) || beanType.isArray()) {
        return; // use @Input(include) to list parameter names, at least? Or mix with hdiv's form builder?
    }
    try {
        Constructor[] constructors = beanType.getConstructors();
        // find default ctor
        Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
        // find ctor with JsonCreator ann
        if (constructor == null) {
            constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
        }
        Assert.notNull(constructor,
                "no default constructor or JsonCreator found for type " + beanType.getName());
        int parameterCount = constructor.getParameterTypes().length;

        if (parameterCount > 0) {
            Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();

            Class[] parameters = constructor.getParameterTypes();
            int paramIndex = 0;
            for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
                for (Annotation annotation : annotationsOnParameter) {
                    if (JsonProperty.class == annotation.annotationType()) {
                        JsonProperty jsonProperty = (JsonProperty) annotation;

                        // TODO use required attribute of JsonProperty for required fields
                        String paramName = jsonProperty.value();
                        Class parameterType = parameters[paramIndex];
                        Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                                paramName);
                        MethodParameter methodParameter = new MethodParameter(constructor, paramIndex);

                        addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter,
                                annotatedParameters, parentParamName, paramName, parameterType, propertyValue,
                                knownFields);
                        paramIndex++; // increase for each @JsonProperty
                    }
                }
            }
            Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator "
                    + constructor.getName() + " are annotated with @JsonProperty");
        }

        Set<String> knownConstructorFields = new HashSet<String>(uberFields.size());
        for (UberField sirenField : uberFields) {
            knownConstructorFields.add(sirenField.getName());
        }

        // TODO support Option provider by other method args?
        Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType);

        // add input field for every setter
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) {
            final Method writeMethod = propertyDescriptor.getWriteMethod();
            String propertyName = propertyDescriptor.getName();

            if (writeMethod == null || knownFields.contains(parentParamName + propertyName)) {
                continue;
            }
            final Class<?> propertyType = propertyDescriptor.getPropertyType();

            Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, propertyName);
            MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0);

            addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter,
                    annotatedParameters, parentParamName, propertyName, propertyType, propertyValue,
                    knownConstructorFields);
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to write input fields for constructor", e);
    }
}

From source file:dk.netarkivet.archive.webinterface.BatchGUI.java

/**
 * Creates the HTML code for the arguments of the constructor. It reads the resources for the batchjob, where the
 * metadata for the constructor is defined in the 'resources' annotation for the class.
 * <p>/* w  w  w .  j av a  2s. co m*/
 * <br/>
 * E.g. The UrlSearch batchjob. Which has the following resources:<br/>
 *
 * @param c The class whose constructor should be used.
 * @param locale The language package.
 * @return The HTML code for the arguments for executing the batchjob.
 * @Resource(name="regex", description="The regular expression for the " + "urls.", type=java.lang.String.class)<br/>
 * @Resource(name="mimetype", type=java.lang.String.class)<br/>
 * Though the batchjob takes three arguments (thus one undefined). <br/>
 * <br/>
 * <p>
 * Arguments:&lt;br/&gt;<br/>
 * regex (The regular expression for the urls.)&lt;br/&gt;<br/>
 * &lt;input name="arg1" size="50" value=""&gt;&lt;br/&gt;<br/>
 * mimetype&lt;br/&gt;<br/>
 * &lt;input name="arg2" size="50" value=""&gt;&lt;br/&gt;<br/>
 * Argument 3 (missing argument metadata)&lt;br/&gt;<br/>
 * &lt;input name="arg3" size="50" value=""&gt;&lt;br/&gt;<br/>
 * <p>
 * <br/>
 * Which will look like: <br/>
 * <br/>
 * <p>
 * Arguments:<br/>
 * regex (The regular expression for the urls.)<br/>
 * <input name="arg1" size="50" value="" /><br/>
 * mimetype<br/>
 * <input name="arg2" size="50" value="" /><br/>
 * Argument 3 (missing argument metadata)<br/>
 * <input name="arg3" size="50" value="" /><br/>
 * <p>
 * TODO this does not work until batchjobs can be used with arguments.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static String getHTMLarguments(Class c, Locale locale) {
    Constructor con = findStringConstructor(c);
    Type[] params = con.getParameterTypes();

    // If no parameters, then return no content (new line).
    if (params.length < 1) {
        return "<br/>\n";
    }

    // Retrieve the resources (metadata for the arguments).
    Resources r = (Resources) c.getAnnotation(Resources.class);
    if (r == null) {
        return "<br/>\n";
    }
    Resource[] resource = r.value();

    StringBuilder res = new StringBuilder();

    res.append(I18N.getString(locale, "batchpage;Arguments", new Object[] {}) + ":<br/>\n");

    if (resource.length < params.length) {
        // warn about no metadata.
        res.append(I18N.getString(locale, "batchpage;Bad.argument.metadata.for.the.constructor", con.toString())
                + ".<br/>\n");
        // make default 'arguments'.
        for (int i = 1; i <= params.length; i++) {
            res.append(I18N.getString(locale, "batchpage;Argument.i", i) + "<br/>\n");
            res.append("<input name=\"arg" + i + "\" size=\"" + Constants.HTML_INPUT_SIZE
                    + "\" value=\"\"><br/>\n");
        }
    } else {
        // handle the case, when there is arguments.
        int parmIndex = 0;
        // retrieve the arguments from the resources.
        for (int i = 0; i < resource.length && parmIndex < params.length; i++) {
            if (resource[i].type() == params[parmIndex]) {
                // Use the resource to describe the argument.
                parmIndex++;
                res.append(resource[i].name());
                if (resource[i].description() != null && !resource[i].description().isEmpty()) {
                    res.append(" (" + resource[i].description() + ")");
                }
                res.append("<br/>\n");
                res.append("<input name=\"arg" + parmIndex + "\" size=\"" + Constants.HTML_INPUT_SIZE
                        + "\" value=\"\"><br/>\n");
            }
        }
        // If some arguments did not have a resource description, then
        // use a default 'unknown argument' input box.
        if (parmIndex < params.length) {
            for (int i = parmIndex + 1; i <= params.length; i++) {
                res.append(I18N.getString(locale, "batchpage;Argument.i.missing.argument.metadata", i)
                        + "<br/>\n");
                res.append("<input name=\"arg" + i + "\" size=\"" + Constants.HTML_INPUT_SIZE
                        + "\" value=\"\"><br/>\n");
            }
        }
    }

    res.append("<br/>\n");

    return res.toString();
}

From source file:org.xmlsh.util.JavaUtils.java

public static <T> Constructor<T> getBestConstructor(Constructor<T>[] constructors, Object... argValues)
        throws InvalidArgumentException {

    Constructor<T> best = null;
    int bestConversions = 0;

    // TODO how to choose best match

    for (Constructor<T> c : constructors) {
        Class<?>[] params = c.getParameterTypes();
        if (params.length == argValues.length) {
            int conversions = 0;
            int i = 0;
            for (Object obj : argValues) {
                int convert = canConvertObject(obj, params[i]);
                if (convert < 0)
                    break;
                conversions += convert;//  w w w.  j  a  v a2s.  com
                i++;
            }
            if (i == params.length) {
                // Find best match
                if (best == null || conversions < bestConversions) {
                    best = c;
                    bestConversions = conversions;

                }
            }
        }

    }
    return best;
}

From source file:org.xmlsh.util.JavaUtils.java

public static Constructor<?> getBestMatch(List<XValue> args, Constructor<?>[] constructors)
        throws CoreException {

    Constructor<?> best = null;
    int bestConversions = 0;

    // TODO how to choose best match

    for (Constructor<?> c : constructors) {
        Class<?>[] params = c.getParameterTypes();
        if (params.length == args.size()) {
            int conversions = 0;
            int i = 0;
            for (XValue arg : args) {
                int convert = arg.canConvert(params[i]);
                if (convert < 0)
                    break;
                conversions += convert;/*from www .ja  v  a2 s. co m*/
                i++;
            }
            if (i == params.length) {
                // Find best match
                if (best == null || conversions < bestConversions) {
                    best = c;
                    bestConversions = conversions;

                }

            }

        }

    }
    return best;
}