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:ch.algotrader.config.ConfigBeanFactory.java

@SuppressWarnings("unchecked")
public <T> T create(final ConfigParams configParams, final Class<T> clazz) {

    Validate.notNull(configParams, "ConfigParams is null");
    Validate.notNull(clazz, "Target class is null");

    Constructor<?>[] constructors = clazz.getConstructors();
    if (constructors.length != 1) {

        throw new ConfigBeanCreationException(
                clazz.getName() + " config bean class is expected to declare one constructor only");
    }/* w  w w.java2s .  c  o  m*/

    Constructor<?> constructor = constructors[0];
    Annotation[][] parameterAnnotations = constructor.getParameterAnnotations();
    Class<?>[] parameterTypes = constructor.getParameterTypes();
    if (parameterTypes.length != parameterAnnotations.length) {

        throw new ConfigBeanCreationException(clazz.getName() + " config bean metadata is inconsistent");
    }

    Object[] paramValues = new Object[parameterTypes.length];
    for (int i = 0; i < parameterTypes.length; i++) {

        Class<?> paramType = parameterTypes[i];
        Annotation[] annotations = parameterAnnotations[i];
        ConfigName configName = null;
        for (Annotation annotation : annotations) {
            if (annotation.annotationType().equals(ConfigName.class)) {
                configName = (ConfigName) annotation;
                break;
            }
        }
        if (configName == null) {

            throw new ConfigBeanCreationException(
                    clazz.getName() + " config bean parameter does not have mandatory metadata");
        }
        Object paramValue = configParams.getParameter(configName.value(), paramType);
        if (paramValue == null && !configName.optional()) {
            throw new ConfigBeanCreationException("Config parameter '" + configName.value() + "' is undefined");

        }
        paramValues[i] = paramValue;
    }
    try {
        return (T) constructor.newInstance(paramValues);
    } catch (InstantiationException | InvocationTargetException | IllegalAccessException ex) {
        throw new ConfigBeanCreationException(ex);
    }
}

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

public static <T> T convert(Object value, Class<T> targetClass) throws InvalidArgumentException {

    assert (targetClass != null);

    assert (value != null);
    if (targetClass.isInstance(value))
        return targetClass.cast(value);

    Class<?> sourceClass = value.getClass();

    // Asking for an XdmValue class
    if (XdmValue.class.isAssignableFrom(targetClass)) {
        if (value instanceof XdmNode)
            return (T) (XdmValue) value;

        if (targetClass.isAssignableFrom(XdmAtomicValue.class)) {

            // Try some smart conversions of all types XdmAtomicValue knows
            if (value instanceof Boolean)
                return (T) new XdmAtomicValue(((Boolean) value).booleanValue());
            else if (value instanceof Double)
                return (T) new XdmAtomicValue(((Double) value).doubleValue());
            else if (value instanceof Float)
                return (T) new XdmAtomicValue(((Float) value).floatValue());

            else if (value instanceof BigDecimal)
                return (T) new XdmAtomicValue((BigDecimal) value);
            else if (value instanceof BigDecimal)
                return (T) new XdmAtomicValue((BigDecimal) value);

            else if (value instanceof URI)
                return (T) new XdmAtomicValue((URI) value);
            else if (value instanceof Long)
                return (T) new XdmAtomicValue((Long) value);
            else if (value instanceof QName)
                return (T) new XdmAtomicValue((QName) value);

            // Still wanting an xdm value
        }/*from   www.j a va 2 s .com*/

        if (isAtomic(value))
            return (T) new XdmAtomicValue(value.toString());

    }

    boolean bAtomic = isAtomic(value);
    Class<?> vclass = value.getClass();

    if (targetClass.isPrimitive() && bAtomic) {

        /* Try to match non-primative types
        */
        if (targetClass == Integer.TYPE) {
            if (vclass == Long.class)
                value = Integer.valueOf(((Long) value).intValue());
            else if (vclass == Short.class)
                value = Integer.valueOf(((Short) value).intValue());
            else if (vclass == Byte.class)
                value = Integer.valueOf(((Byte) value).intValue());
            else
                value = Integer.valueOf(value.toString());

        } else if (targetClass == Long.TYPE) {
            if (vclass == Integer.class)
                value = Long.valueOf(((Integer) value).intValue());
            else if (vclass == Short.class)
                value = Long.valueOf(((Short) value).intValue());
            else if (vclass == Byte.class)
                value = Long.valueOf(((Byte) value).intValue());
            value = Long.valueOf(value.toString());

        }

        else if (targetClass == Short.TYPE) {
            if (vclass == Integer.class)
                value = Short.valueOf((short) ((Integer) value).intValue());
            else if (vclass == Long.class)
                value = Short.valueOf((short) ((Long) value).intValue());
            else if (vclass == Byte.class)
                value = Short.valueOf((short) ((Byte) value).intValue());
            value = Short.valueOf(value.toString());

        }

        else if (targetClass == Byte.TYPE) {
            if (vclass == Integer.class)
                value = Byte.valueOf((byte) ((Integer) value).intValue());
            else if (vclass == Long.class)
                value = Byte.valueOf((byte) ((Long) value).intValue());
            else if (vclass == Short.class)
                value = Byte.valueOf((byte) ((Short) value).intValue());
            value = Byte.valueOf(value.toString());
        } else
            ; // skip

        return (T) value;
    }

    // Bean constructor

    Constructor<?> cnst = getBeanConstructor(targetClass, sourceClass);
    if (cnst != null)
        try {
            return (T) cnst.newInstance(convert(value, cnst.getParameterTypes()[0]));
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {

            mLogger.debug("Exception converting argument for constructor", e);
        }

    // Cast through string

    String svalue = value.toString();

    if (targetClass == Integer.class)
        value = Integer.valueOf(svalue);
    else if (targetClass == Long.class)
        value = Long.valueOf(svalue);
    else if (targetClass == Short.class)
        value = Short.valueOf(svalue);
    else if (targetClass == Float.class)
        value = Float.valueOf(svalue);
    else if (targetClass == Double.class)
        value = Double.valueOf(svalue);
    else
        value = null;

    return (T) value;

}

From source file:blue.lapis.pore.impl.event.PoreEventImplTest.java

@Test
public void checkConstructor() throws Throwable {
    for (Constructor<?> constructor : eventImpl.getConstructors()) {
        Class<?>[] parameters = constructor.getParameterTypes();
        if (parameters.length == 1) {
            Class<?> handle = parameters[0];
            if (org.spongepowered.api.event.Event.class.isAssignableFrom(handle)) {
                // Check for null check
                try {
                    constructor.newInstance(new Object[] { null });
                } catch (InvocationTargetException e) {
                    Throwable cause = e.getCause();
                    if (cause != null) {
                        if (cause instanceof NullPointerException
                                && Objects.equal(cause.getMessage(), "handle")) {
                            return;
                        }//from w  w w . j  av a2s  .c om

                        throw cause;
                    }

                    throw e;
                }

                fail(eventImpl.getSimpleName() + ": missing null-check for handle");
            }
        }
    }

    fail(eventImpl.getSimpleName() + ": missing handle constructor");
}

From source file:com.medallia.tiny.ObjectProvider.java

/** Same as {@link #makeArgsFor(Method)}, but for a {@link Constructor} */
public Object[] makeArgsFor(Constructor cons) {
    return makeArgsFor(cons.getParameterTypes(), cons.getParameterAnnotations());
}

From source file:fitnesse.slim.StatementExecutor.java

private Constructor<?> getConstructor(Constructor<?>[] constructors, Object[] args) {
    for (Constructor<?> constructor : constructors) {
        Class<?> arguments[] = constructor.getParameterTypes();
        if (arguments.length == args.length)
            return constructor;
    }/*from   www .j a v  a 2  s  . c  o  m*/
    return null;
}

From source file:org.jbpm.formModeler.core.model.PojoDataHolder.java

protected Object createInstance(Class pojoClass) throws Exception {
    for (Constructor constructor : pojoClass.getConstructors()) {
        if (constructor.getParameterTypes().length == 0) {
            return constructor.newInstance();
        }//from ww  w.j a  v a2  s. co m
    }
    return null;
}

From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java

/**
 * Find constructor.// w ww.j  a v a 2s  . c o m
 *
 * @param <T> the generic type
 * @param clazz the clazz
 * @param args the args
 * @return the constructor
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> findConstructor(Class<T> clazz, Object[] args) {
    nextMethod: for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {

        Class<?>[] argClazzes = constructor.getParameterTypes();
        if (argClazzes.length != args.length) {
            continue;
        }
        for (int i = 0; i < args.length; ++i) {
            Object a = args[i];
            Class<?> ac = argClazzes[i];
            if (a != null && ac.isAssignableFrom(a.getClass()) == false) {
                continue nextMethod;
            }
        }
        return (Constructor<T>) constructor;
    }
    return null;
}

From source file:org.pentaho.osgi.legacy.LegacyPluginExtenderFactory.java

/**
 * Creates the object using a child-first classloader that uses local bundle bytecode first (so that it will be the
 * classloader for bundle classes created using this method which is necessary for correct loading of imports), the
 * bundleContext's classloader second, and the Kettle plugin's classloader third.
 * <p/>/*from  w ww .  j a v  a 2  s .c  om*/
 * This allows bundles to implement interfaces known only to OSGi using classes only known to Ketle plugins (or vice
 * versa).
 *
 * @param className the classname to instantiate
 * @param arguments the arguments to use to instantiate the class
 * @return the instantiated class
 * @throws ClassNotFoundException
 * @throws InvocationTargetException
 * @throws InstantiationException
 * @throws KettlePluginException
 * @throws IllegalAccessException
 * @throws InterruptedException
 */
public Object create(String className, List<Object> arguments) throws ClassNotFoundException,
        IllegalAccessException, InstantiationException, InvocationTargetException {
    Class<?> clazz = Class.forName(className, true, legacyBridgingClassloader);
    if (arguments == null || arguments.size() == 0) {
        return clazz.newInstance();
    }
    for (Constructor<?> constructor : clazz.getConstructors()) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if (parameterTypes.length == arguments.size()) {
            boolean match = true;
            for (int i = 0; i < parameterTypes.length; i++) {
                Object o = arguments.get(i);
                if (o != null && !parameterTypes[i].isInstance(o)) {
                    match = false;
                    break;
                }
            }
            if (match) {
                return constructor.newInstance(arguments.toArray());
            }
        }
    }
    throw new InstantiationException(
            "Unable to find constructor for class " + className + " with arguments " + arguments);
}

From source file:org.apache.poi.util.MethodUtils.java

public static <T> Constructor<T> getMatchingAccessibleConstructor(Class<T> clazz, Class[] parameterTypes) {
    // trace logging
    Log log = LogFactory.getLog(MethodUtils.class);
    MethodDescriptor md = new MethodDescriptor(clazz, "dummy", parameterTypes, false);

    // see if we can find the method directly
    // most of the time this works and it's much faster
    try {/*www  .jav  a  2 s .c o m*/
        Constructor<T> constructor = clazz.getConstructor(parameterTypes);
        if (log.isTraceEnabled()) {
            log.trace("Found straight match: " + constructor);
            log.trace("isPublic:" + Modifier.isPublic(constructor.getModifiers()));
        }

        setMethodAccessible(constructor); // Default access superclass workaround

        return constructor;

    } catch (NoSuchMethodException e) {
        /* SWALLOW */ }

    // search through all methods 
    int paramSize = parameterTypes.length;
    Constructor<T> bestMatch = null;
    Constructor<?>[] constructors = clazz.getConstructors();
    float bestMatchCost = Float.MAX_VALUE;
    float myCost = Float.MAX_VALUE;
    for (int i = 0, size = constructors.length; i < size; i++) {
        // compare parameters
        Class[] methodsParams = constructors[i].getParameterTypes();
        int methodParamSize = methodsParams.length;
        if (methodParamSize == paramSize) {
            boolean match = true;
            for (int n = 0; n < methodParamSize; n++) {
                if (log.isTraceEnabled()) {
                    log.trace("Param=" + parameterTypes[n].getName());
                    log.trace("Method=" + methodsParams[n].getName());
                }
                if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
                    if (log.isTraceEnabled()) {
                        log.trace(methodsParams[n] + " is not assignable from " + parameterTypes[n]);
                    }
                    match = false;
                    break;
                }
            }

            if (match) {
                // get accessible version of method
                Constructor<T> cons = (Constructor<T>) constructors[i];
                myCost = getTotalTransformationCost(parameterTypes, cons.getParameterTypes());
                if (myCost < bestMatchCost) {
                    bestMatch = cons;
                    bestMatchCost = myCost;
                }
            }
        }
    }
    if (bestMatch == null) {
        // didn't find a match
        log.trace("No match found.");
    }

    return bestMatch;
}

From source file:org.unitils.core.context.Context.java

protected Constructor<?> getConstructor(Class<?> implementationType) {
    Constructor<?>[] constructors = implementationType.getConstructors();
    // use default constructor if there are no constructors
    if (constructors.length == 0) {
        return null;
    }/*  w w  w .j  av  a 2  s  .c om*/
    // try no-args constructor if there is more than one constructor
    if (constructors.length > 1) {
        for (Constructor<?> constructor : constructors) {
            if (constructor.getParameterTypes().length == 0) {
                return null;
            }
        }
        throw new UnitilsException(
                "Found more than 1 constructor in implementation type " + implementationType.getName());
    }
    return constructors[0];
}