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:edu.umich.flowfence.common.QMDescriptor.java

public static QMDescriptor forConstructor(Context context, Constructor<?> ctor) {
    return forConstructor(context, ctor.getDeclaringClass(), ctor.getParameterTypes());
}

From source file:edu.umich.oasis.common.SodaDescriptor.java

public static SodaDescriptor forConstructor(Context context, Constructor<?> ctor) {
    return forConstructor(context, ctor.getDeclaringClass(), ctor.getParameterTypes());
}

From source file:com.opengamma.util.ReflectionUtils.java

/**
 * Finds a constructor from a Class.//www.  j  a v  a  2s . c  om
 * 
 * @param <T> the type
 * @param type  the type to create, not null
 * @param arguments  the arguments, not null
 * @return the constructor, not null
 * @throws RuntimeException if the class cannot be loaded
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> findConstructorByArguments(final Class<T> type, final Object... arguments) {
    Class<?>[] paramTypes = new Class<?>[arguments.length];
    for (int i = 0; i < arguments.length; i++) {
        paramTypes[i] = (arguments[i] != null ? arguments[i].getClass() : null);
    }
    Constructor<?> matched = null;
    for (Constructor<?> constructor : type.getConstructors()) {
        if (org.apache.commons.lang.ClassUtils.isAssignable(paramTypes, constructor.getParameterTypes())) {
            if (matched == null) {
                matched = constructor;
            } else {
                throw new OpenGammaRuntimeException("Multiple matching constructors: " + type);
            }
        }
    }
    if (matched == null) {
        throw new OpenGammaRuntimeException("No matching constructor: " + type);
    }
    return (Constructor<T>) matched;
}

From source file:org.force66.beantester.utils.InstantiationUtils.java

public static Object safeNewInstance(ValueGeneratorFactory factory, Class<?> klass) {
    Validate.notNull(klass, "Null class not allowed.");
    Constructor<?> ctor = findPublicConstructor(klass);
    if (ctor == null) {
        throw new BeanTesterException("No public constructor found -- value generation isn't possible")
                .addContextValue("class", klass.getName());
    }/*from   www . jav  a 2 s.  c o m*/
    if (ctor.getParameterTypes().length == 0) {
        return safeNewInstance(klass, null);
    }

    ValueGenerator<?> generator = null;
    List<Object> constructorArgs = new ArrayList<Object>();
    for (Class<?> argType : ctor.getParameterTypes()) {
        generator = factory.forClass(argType);
        if (generator == null) {
            throw new BeanTesterException("Value can't be generated for constructor argument")
                    .addContextValue("class", klass.getName()).addContextValue("constructor", ctor)
                    .addContextValue("argument type", argType.getName());
        }
        constructorArgs.add(generator.makeValues()[0]);
    }

    return safeNewInstance(klass, constructorArgs.toArray());
}

From source file:info.novatec.testit.livingdoc.util.ClassUtils.java

private static boolean typesMatch(Constructor<?> constructor, Object[] args) {
    if (!arityMatches(constructor, args)) {
        return false;
    }// ww  w  . j ava  2s .  c om

    Class<?>[] parameterTypes = constructor.getParameterTypes();
    parameterTypes = changePrimitivesTypesToNonOnes(parameterTypes);

    for (int i = 0; i < args.length; i++) {
        if (!parameterTypes[i].isInstance(args[i])) {
            return false;
        }
    }

    return true;
}

From source file:net.sf.ehcache.config.BeanHandler.java

/**
 * Creates a child object./*  w  w w .j  a v  a 2s . c  om*/
 */
private static Object createInstance(Object parent, Class childClass) throws Exception {
    final Constructor[] constructors = childClass.getConstructors();
    ArrayList candidates = new ArrayList();
    for (int i = 0; i < constructors.length; i++) {
        final Constructor constructor = constructors[i];
        final Class[] params = constructor.getParameterTypes();
        if (params.length == 0) {
            candidates.add(constructor);
        } else if (params.length == 1 && params[0].isInstance(parent)) {
            candidates.add(constructor);
        }
    }
    switch (candidates.size()) {
    case 0:
        throw new Exception("No constructor for class " + childClass.getName());
    case 1:
        break;
    default:
        throw new Exception("Multiple constructors for class " + childClass.getName());
    }

    final Constructor constructor = (Constructor) candidates.remove(0);
    if (constructor.getParameterTypes().length == 0) {
        return constructor.newInstance(new Object[] {});
    } else {
        return constructor.newInstance(new Object[] { parent });
    }
}

From source file:org.apache.openaz.xacml.util.FactoryFinder.java

public static <T> T newInstance(String className, Class<T> classExtends, ClassLoader cl, boolean doFallback,
        Properties xacmlProperties) throws FactoryException {
    try {/* w ww  .j  av  a2  s .c  om*/
        Class<?> providerClass = getProviderClass(className, cl, doFallback);
        if (classExtends.isAssignableFrom(providerClass)) {
            Object instance = null;
            if (xacmlProperties == null) {
                instance = providerClass.newInstance();
            } else {
                //
                // Search for a constructor that takes Properties
                //
                for (Constructor<?> constructor : providerClass.getDeclaredConstructors()) {
                    Class<?>[] params = constructor.getParameterTypes();
                    if (params.length == 1 && params[0].isAssignableFrom(Properties.class)) {
                        instance = constructor.newInstance(xacmlProperties);
                    }
                }
                if (instance == null) {
                    logger.warn("No constructor that takes a Properties object.");
                    instance = providerClass.newInstance();
                }
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Created new instance of " + providerClass + " using ClassLoader: " + cl);
            }
            return classExtends.cast(instance);
        } else {
            throw new ClassNotFoundException(
                    "Provider " + className + " does not extend " + classExtends.getCanonicalName());
        }
    } catch (ClassNotFoundException ex) {
        throw new FactoryException("Provider " + className + " not found", ex);
    } catch (Exception ex) {
        throw new FactoryException("Provider " + className + " could not be instantiated: " + ex.getMessage(),
                ex);
    }
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.LegacyExceptionUtil.java

/**
 * Find a construcor that matches this set of properties
 *
 * @param cls//from  w w  w. ja va 2  s .  co  m
 * @param pdList
 * @param childNames returned in the order that they occur in the constructor
 * @return Constructor or null
 */
private static Constructor findConstructor(Class cls, List<PropertyDescriptorPlus> pdList,
        List<String> childNames) {
    Constructor[] constructors = cls.getConstructors();
    Constructor constructor = null;
    if (constructors != null) {
        for (int i = 0; i < constructors.length && constructor == null; i++) {
            Constructor tryConstructor = constructors[i];
            if (tryConstructor.getParameterTypes().length == pdList.size()) {
                // Try and find the best match using the property types
                List<PropertyDescriptorPlus> list = new ArrayList<PropertyDescriptorPlus>(pdList);
                List<PropertyDescriptorPlus> args = new ArrayList<PropertyDescriptorPlus>();

                Class[] parms = tryConstructor.getParameterTypes();
                boolean valid = true;

                // Assume the message is first in the constructor
                for (int j = 0; j < list.size(); j++) {
                    if ("message".equals(list.get(j).getPropertyName())) {
                        args.add(list.remove(j));
                    }
                }
                if (args.size() != 1 || !parms[0].isAssignableFrom(args.get(0).getPropertyType())) {
                    valid = false;
                }

                // Now process the rest of the args
                for (int j = 1; j < parms.length && valid; j++) {
                    // Find a compatible argument
                    Class parm = parms[j];
                    boolean found = false;
                    for (int k = 0; k < list.size() && !found; k++) {
                        Class arg = list.get(k).getPropertyType();
                        if (parm.isAssignableFrom(arg)) {
                            found = true;
                            args.add(list.remove(k));
                        }
                    }
                    // If no compatible argument then this constructor is not valid
                    if (!found) {
                        valid = false;
                    }
                }
                // A constructor is found
                if (valid) {
                    constructor = tryConstructor;
                    for (int index = 0; index < args.size(); index++) {
                        childNames.add(args.get(index).getPropertyName());
                    }
                }
            }
        }
    }

    return constructor;
}

From source file:com.oltpbenchmark.util.ClassUtil.java

/**
 * //ww  w. java  2s  . c  o m
 * @param <T>
 * @param target_class
 * @param params
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> getConstructor(Class<T> target_class, Class<?>... params) {
    NoSuchMethodException error = null;
    try {
        return (target_class.getConstructor(params));
    } catch (NoSuchMethodException ex) {
        // The first time we get this it can be ignored
        // We'll try to be nice and find a match for them
        error = ex;
    }
    assert (error != null);

    if (LOG.isDebugEnabled()) {
        LOG.debug("TARGET CLASS:  " + target_class);
        LOG.debug("TARGET PARAMS: " + Arrays.toString(params));
    }

    List<Class<?>> paramSuper[] = (List<Class<?>>[]) new List[params.length];
    for (int i = 0; i < params.length; i++) {
        paramSuper[i] = ClassUtil.getSuperClasses(params[i]);
        if (LOG.isDebugEnabled())
            LOG.debug("  SUPER[" + params[i].getSimpleName() + "] => " + paramSuper[i]);
    } // FOR

    for (Constructor<?> c : target_class.getConstructors()) {
        Class<?> cTypes[] = c.getParameterTypes();
        if (LOG.isDebugEnabled()) {
            LOG.debug("CANDIDATE: " + c);
            LOG.debug("CANDIDATE PARAMS: " + Arrays.toString(cTypes));
        }
        if (params.length != cTypes.length)
            continue;

        for (int i = 0; i < params.length; i++) {
            List<Class<?>> cSuper = ClassUtil.getSuperClasses(cTypes[i]);
            if (LOG.isDebugEnabled())
                LOG.debug("  SUPER[" + cTypes[i].getSimpleName() + "] => " + cSuper);
            if (CollectionUtils.intersection(paramSuper[i], cSuper).isEmpty() == false) {
                return ((Constructor<T>) c);
            }
        } // FOR (param)
    } // FOR (constructors)
    throw new RuntimeException("Failed to retrieve constructor for " + target_class.getSimpleName(), error);
}

From source file:org.grouplens.grapht.util.ClassProxy.java

private static void checksumClass(Class<?> type, MessageDigest digest) {
    // we compute a big hash of all the members of the class, and its superclasses.

    List<String> members = new ArrayList<String>();
    for (Constructor<?> c : type.getDeclaredConstructors()) {
        if (isInjectionSensitive(c)) {
            members.add(String.format("%s(%s)", c.getName(), StringUtils.join(c.getParameterTypes(), ", ")));
        }/* w  w w. ja  va 2s  .  c  o  m*/
    }
    for (Method m : type.getDeclaredMethods()) {
        if (isInjectionSensitive(m)) {
            members.add(String.format("%s(%s): %s", m.getName(), StringUtils.join(m.getParameterTypes(), ", "),
                    m.getReturnType()));
        }
    }
    for (Field f : type.getDeclaredFields()) {
        if (isInjectionSensitive(f)) {
            members.add(f.getName() + ":" + f.getType().getName());
        }
    }

    Collections.sort(members);

    Class<?> sup = type.getSuperclass();
    if (sup != null) {
        checksumClass(sup, digest);
    }
    for (String mem : members) {
        digest.update(mem.getBytes(UTF8));
    }
}